נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
28
חלקPart 5: Java מודרנית וכליםModern Java & tools כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

חריגות checked מול unchecked ו-try-with-resourcesChecked vs unchecked exceptions & try-with-resources

היררכיית החריגות, throws, חריגות משלכם, ו-try-with-resources שסוגר משאבים לבד.

The exception hierarchy, throws, your own exceptions, and try-with-resources that closes resources by itself.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • חריגה checked: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException. javac מחייב לתפוס אותה או להכריז עליה ב-throws. מתאימה למצבים צפויים: קובץ חסר, רשת נפלה.checked exception: An exception extending Exception (not RuntimeException), like IOException. javac forces you to catch it or declare it with throws. It fits expected situations: a missing file, a network failure.
  • חריגה unchecked: חריגה שיורשת מ-RuntimeException (IllegalArgumentException, NullPointerException). לא חובה להכריז. בדרך כלל מסמנת באג אצל מי שקרא.unchecked exception: An exception extending RuntimeException (IllegalArgumentException, NullPointerException). No declaration required. It usually signals a bug in the caller.
  • throws: static String load(...) throws IOException: "המתודה הזו עלולה לזרוק IOException, ומי שקורא לה צריך לטפל".throws: static String load(...) throws IOException: "this method may throw an IOException, and its caller must deal with it".
  • חריגה משלכם: class BookNotFoundException extends Exception: שם שמסביר את המצב, הודעה ברורה, ושדות נוספים אם צריך.custom exception: class BookNotFoundException extends Exception: a name that explains the situation, a clear message, and extra fields if needed.
  • סיבה (cause): new DataException("line 2 bad", e) עוטף את החריגה המקורית. getCause() מחזיר אותה, וה-stack trace מראה את שתיהן.cause: new DataException("line 2 bad", e) wraps the original exception. getCause() returns it, and the stack trace shows both.
  • try-with-resources: try (Res r = new Res()) { ... }: בסוף הבלוק Java קוראת ל-close() לבד, גם אם נזרקה חריגה. כמה משאבים נסגרים בסדר הפוך.try-with-resources: try (Res r = new Res()) { ... }: at the end of the block Java calls close() itself, even if an exception was thrown. Several resources close in reverse order.
  • multi-catch: catch (ArithmeticException | NumberFormatException e): טיפול אחד לכמה סוגי חריגות.multi-catch: catch (ArithmeticException | NumberFormatException e): one handler for several exception types.

02checked: javac מחייב לטפלchecked: javac forces you to handle it

load מכריזה throws IOException. main קורא לה בלי try ובלי throws, ו-javac לא מקמפל.

load declares throws IOException. main calls it with no try and no throws, and javac won't compile.

טעות נפוצהCommon mistake

checked: javac מחייב לטפל

checked: javac forces you to handle it

Main.java
import java.io.IOException;

public class Main {
    static String load(String name) throws IOException {
        if (name.isEmpty()) {
            throw new IOException("no file name");
        }
        return "data of " + name;
    }

    public static void main(String[] args) {
        System.out.println(load("shelf.txt"));
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:12: error: unreported exception IOException; must be caught or declared to be thrown
        System.out.println(load("shelf.txt"));
                               ^
1 error
בעברית פשוטה: In plain words: unreported exception IOException; must be caught or declared to be thrown: תופסים ב-try/catch, או מוסיפים throws גם ל-main.unreported exception IOException; must be caught or declared to be thrown: catch it in try/catch, or add throws to main too.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03חריגה משלכם, עם סיבהYour own exception, with a cause

InvalidYearException היא checked. parseYear הופכת את ה-NumberFormatException הטכני להודעה שמבינים, ושומרת אותו כ-cause.

InvalidYearException is checked. parseYear turns the technical NumberFormatException into a message people understand, and keeps it as the cause.

Main.java
public class Main {
    static int parseYear(String text) throws InvalidYearException {
        try {
            int y = Integer.parseInt(text);
            if (y < 0 || y > 2026) {
                throw new InvalidYearException("year out of range: " + y);
            }
            return y;
        } catch (NumberFormatException e) {
            throw new InvalidYearException("not a year: " + text, e);
        }
    }

    public static void main(String[] args) {
        for (String t : new String[]{"1965", "3000", "19x5"}) {
            try {
                System.out.println("ok " + parseYear(t));
            } catch (InvalidYearException e) {
                System.out.println("bad: " + e.getMessage() + (e.getCause() != null ? " (cause: " + e.getCause().getClass().getSimpleName() + ")" : ""));
            }
        }
    }
}

class InvalidYearException extends Exception {
    InvalidYearException(String message) {
        super(message);
    }

    InvalidYearException(String message, Throwable cause) {
        super(message, cause);
    }
}
פלטOutput
ok 1965
bad: year out of range: 3000
bad: not a year: 19x5 (cause: NumberFormatException)
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04try-with-resourcestry-with-resources

שני משאבים נפתחים, הגוף זורק חריגה, ובכל זאת שניהם נסגרים, בסדר הפוך, ורק אחר כך ה-catch רץ.

Two resources open, the body throws, and still both close, in reverse order, and only then does the catch run.

Main.java
public class Main {
    public static void main(String[] args) {
        try (Res a = new Res("db"); Res b = new Res("file")) {
            System.out.println("working");
            throw new IllegalStateException("oops");
        } catch (IllegalStateException e) {
            System.out.println("caught " + e.getMessage());
        }
    }
}

class Res implements AutoCloseable {
    private final String name;

    Res(String name) {
        this.name = name;
        System.out.println("open " + name);
    }

    @Override
    public void close() {
        System.out.println("close " + name);
    }
}
פלטOutput
open db
open file
working
close file
close db
caught oops
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: unreported exception

Bug hunter: unreported exception

Main.java
import java.io.IOException;

public class Main {
    static String load(String name) throws IOException {
        if (name.isEmpty()) {
            throw new IOException("no file name");
        }
        return "data of " + name;
    }

    public static void main(String[] args) {
        System.out.println(load("shelf.txt"));
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:12: error: unreported exception IOException; must be caught or declared to be thrown
        System.out.println(load("shelf.txt"));
                               ^
1 error
בעברית פשוטה: In plain words: unreported exception IOException; must be caught or declared to be thrown: חובה לטפל ב-checked.unreported exception IOException; must be caught or declared to be thrown: a checked exception must be handled.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

BookNotFoundException (checked) שומרת את הכותר המבוקש ובונה הודעה. Shelf.find מחזירה ספר או זורקת. הדפיסו Found: Book[title=Emma, author=Austen] ואז No book titled 'Hamlet' on the shelf (asked for: Hamlet).

BookNotFoundException (checked) keeps the requested title and builds a message. Shelf.find returns a book or throws. Print Found: Book[title=Emma, author=Austen] then No book titled 'Hamlet' on the shelf (asked for: Hamlet).

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich