חלק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.
הנקודות החשובותKey points
- חריגה checked: חריגה שיורשת מ-
Exception(ולא מ-RuntimeException), כמוIOException.checked exception: An exception extendingException(notRuntimeException), likeIOException. - חריגה unchecked: חריגה שיורשת מ-
RuntimeException(IllegalArgumentException,NullPointerException).unchecked exception: An exception extendingRuntimeException(IllegalArgumentException,NullPointerException). loadמכריזהthrows IOException.loaddeclaresthrows IOException.mainקורא לה בלי try ובלי throws, ו-javac לא מקמפל.maincalls it with no try and no throws, and javac won't compile.InvalidYearExceptionהיא checked.InvalidYearExceptionis checked.parseYearהופכת את ה-NumberFormatExceptionהטכני להודעה שמבינים, ושומרת אותו כ-cause.parseYearturns the technicalNumberFormatExceptioninto 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 extendingException(notRuntimeException), likeIOException. javac forces you to catch it or declare it withthrows. It fits expected situations: a missing file, a network failure. - חריגה uncheckedunchecked exception: חריגה שיורשת מ-
RuntimeException(IllegalArgumentException,NullPointerException). לא חובה להכריז. בדרך כלל מסמנת באג אצל מי שקרא.An exception extendingRuntimeException(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 callsclose()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 extendingException(notRuntimeException), likeIOException. javac forces you to catch it or declare it withthrows. It fits expected situations: a missing file, a network failure. - חריגה uncheckedunchecked exception: חריגה שיורשת מ-
RuntimeException(IllegalArgumentException,NullPointerException). לא חובה להכריז. בדרך כלל מסמנת באג אצל מי שקרא.An exception extendingRuntimeException(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 callsclose()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 declared | checked: javac מחייב לטפלchecked: javac forces you to handle it | 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. |
unreported exception IOException; must be caught or declared | צייד באגים: unreported exceptionBug hunter: unreported exception | 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. |