נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • חריגה checked: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException.checked exception: An exception extending Exception (not RuntimeException), like IOException.
  • חריגה unchecked: חריגה שיורשת מ-RuntimeException (IllegalArgumentException, NullPointerException).unchecked exception: An exception extending RuntimeException (IllegalArgumentException, NullPointerException).
  • load מכריזה throws IOException.load declares throws IOException.
  • main קורא לה בלי try ובלי throws, ו-javac לא מקמפל.main calls it with no try and no throws, and javac won't compile.
  • InvalidYearException היא checked.InvalidYearException is checked.
  • parseYear הופכת את ה-NumberFormatException הטכני להודעה שמבינים, ושומרת אותו כ-cause.parseYear turns the technical NumberFormatException into a message people understand, and keeps it as the cause.
  • שני משאבים נפתחים, הגוף זורק חריגה, ובכל זאת שניהם נסגרים, בסדר הפוך, ורק אחר כך ה-catch רץ.Two resources open, the body throws, and still both close, in reverse order, and only then does the catch run.
  • unreported exception IOException; must be caught or declared to be thrown:unreported exception IOException; must be caught or declared to be thrown:
  • מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException

מונחיםTerms

  • חריגה checkedchecked exception: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException. javac מחייב לתפוס אותה או להכריז עליה ב-throws. מתאימה למצבים צפויים: קובץ חסר, רשת נפלה.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.
  • חריגה uncheckedunchecked exception: חריגה שיורשת מ-RuntimeException (IllegalArgumentException, NullPointerException). לא חובה להכריז. בדרך כלל מסמנת באג אצל מי שקרא.An exception extending RuntimeException (IllegalArgumentException, NullPointerException). No declaration required. It usually signals a bug in the caller.
  • throwsthrows: static String load(...) throws IOException: "המתודה הזו עלולה לזרוק IOException, ומי שקורא לה צריך לטפל".static String load(...) throws IOException: "this method may throw an IOException, and its caller must deal with it".
  • חריגה משלכםcustom exception: class BookNotFoundException extends Exception: שם שמסביר את המצב, הודעה ברורה, ושדות נוספים אם צריך.class BookNotFoundException extends Exception: a name that explains the situation, a clear message, and extra fields if needed.
  • סיבה (cause)cause: new DataException("line 2 bad", e) עוטף את החריגה המקורית. getCause() מחזיר אותה, וה-stack trace מראה את שתיהן.new DataException("line 2 bad", e) wraps the original exception. getCause() returns it, and the stack trace shows both.
  • try-with-resourcestry-with-resources: try (Res r = new Res()) { ... }: בסוף הבלוק Java קוראת ל-close() לבד, גם אם נזרקה חריגה. כמה משאבים נסגרים בסדר הפוך.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-catchmulti-catch: catch (ArithmeticException | NumberFormatException e): טיפול אחד לכמה סוגי חריגות.catch (ArithmeticException | NumberFormatException e): one handler for several exception types.
  • חריגה checkedchecked exception: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException. javac מחייב לתפוס אותה או להכריז עליה ב-throws. מתאימה למצבים צפויים: קובץ חסר, רשת נפלה.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.
  • חריגה uncheckedunchecked exception: חריגה שיורשת מ-RuntimeException (IllegalArgumentException, NullPointerException). לא חובה להכריז. בדרך כלל מסמנת באג אצל מי שקרא.An exception extending RuntimeException (IllegalArgumentException, NullPointerException). No declaration required. It usually signals a bug in the caller.
  • throwsthrows: static String load(...) throws IOException: "המתודה הזו עלולה לזרוק IOException, ומי שקורא לה צריך לטפל".static String load(...) throws IOException: "this method may throw an IOException, and its caller must deal with it".
  • חריגה משלכםcustom exception: class BookNotFoundException extends Exception: שם שמסביר את המצב, הודעה ברורה, ושדות נוספים אם צריך.class BookNotFoundException extends Exception: a name that explains the situation, a clear message, and extra fields if needed.
  • סיבה (cause)cause: new DataException("line 2 bad", e) עוטף את החריגה המקורית. getCause() מחזיר אותה, וה-stack trace מראה את שתיהן.new DataException("line 2 bad", e) wraps the original exception. getCause() returns it, and the stack trace shows both.
  • try-with-resourcestry-with-resources: try (Res r = new Res()) { ... }: בסוף הבלוק Java קוראת ל-close() לבד, גם אם נזרקה חריגה. כמה משאבים נסגרים בסדר הפוך.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-catchmulti-catch: catch (ArithmeticException | NumberFormatException e): טיפול אחד לכמה סוגי חריגות.catch (ArithmeticException | NumberFormatException e): one handler for several exception types.

Cheatsheet

חריגה משלכם, עם סיבהYour own exception, with a cause
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() + ")" : ""));
    }
}
try-with-resourcestry-with-resources
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());
}

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
unreported exception IOException; must be caught or declaredchecked: javac מחייב לטפלchecked: javac forces you to handle itunreported 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.
unreported exception IOException; must be caught or declaredצייד באגים: unreported exceptionBug hunter: unreported exceptionunreported 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.

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