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

חזרה למפגשBack
JavaJava

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

מפגש 28: היררכיית החריגות, throws, חריגות משלכם, ו-try-with-resources שסוגר משאבים לבד.Session 28: The exception hierarchy, throws, your own exceptions, and try-with-resources that closes resources by itself.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • checked: javac מחייב לטפלchecked: javac forces you to handle it
  • חריגה משלכם, עם סיבהYour own exception, with a cause
  • try-with-resourcestry-with-resources
  • טעויות נפוצותCommon mistakes
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

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

  • חריגה 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).
  • throws: static String load(...) throws IOException:throws: static String load(...) throws IOException:
  • חריגה משלכם: class BookNotFoundException extends Exception:custom exception: class BookNotFoundException extends Exception:
  • סיבה (cause): new DataException("line 2 bad", e) עוטף את החריגה המקורית.cause: new DataException("line 2 bad", e) wraps the original exception.
  • try-with-resources: `try (Res r = new Res()) { ...try-with-resources: `try (Res r = new Res()) { ...
נושאTopic 2

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

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

  • 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.
נושאTopic 3

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

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

  • InvalidYearException היא checked.InvalidYearException is checked.
  • parseYear הופכת את ה-NumberFormatException הטכני להודעה שמבינים, ושומרת אותו כ-cause.parseYear turns the technical NumberFormatException into a message people understand, and keeps it as the cause.
נושאTopic 4

try-with-resourcestry-with-resources

try-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.
נושאTopic 5

טעויות נפוצותCommon mistakes

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

  • unreported exception IOException; must be caught or declared to be thrown:unreported exception IOException; must be caught or declared to be thrown:
נושאTopic 6

פרויקט מדףShelf project

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

  • מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException

חריגה 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).

throws: static String load(...) throws IOException:throws: static String load(...) throws IOException:

חריגה משלכם: class BookNotFoundException extends Exception:custom exception: class BookNotFoundException extends Exception:

סיבה (cause): new DataException("line 2 bad", e) עוטף את החריגה המקורית.cause: new DataException("line 2 bad", e) wraps the original exception.

try-with-resources: `try (Res r = new Res()) { ...try-with-resources: `try (Res r = new Res()) { ...

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

איזו מהבאות checked?Which of these is checked?

  • IOExceptionIOException
  • NullPointerExceptionNullPointerException
  • IllegalArgumentExceptionIllegalArgumentException
  • ArithmeticExceptionArithmeticException

IOExceptionIOException

try (A a = ...; B b = ...). באיזה סדר הם נסגרים?try (A a = ...; B b = ...). In which order do they close?

  • a ואז ba then b
  • b ואז ab then a
  • רק aOnly a
  • לא נסגרים אם נזרקה חריגהThey don't close if something threw

b ואז ab then a

מתודה מקבלת דירוג 9 כשמותר 1–5. מה לזרוק?A method gets a rating of 9 when 1–5 is allowed. What should it throw?

  • IllegalArgumentException (unchecked)IllegalArgumentException (unchecked)
  • IOExceptionIOException
  • ExceptionException
  • כלום, להחזיר -1Nothing, return -1

IllegalArgumentException (unchecked)IllegalArgumentException (unchecked)

שנה לא חוקיתAn invalid year

  • כתבו את InvalidYearException (checked, עם בנאי להודעה ובנאי להודעה וסיבה) ואת parseYear מהתזכורת.Write InvalidYearException (checked, with a message constructor and a message-and-cause constructor) and parseYear from the refresher.

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

  • התוכנית מהתזכורת לא מתקמפלת.The program from the refresher doesn't compile.

סדר הסגירהThe closing order

  • משאב Res implements AutoCloseable מדפיס open ו-close.A resource Res implements AutoCloseable prints open and close.

מתי checked ומתי uncheckedWhen checked, when unchecked

  • setRating זורקת IllegalArgumentException (באג אצל מי שקרא), ו-find זורקת NotFoundException checked (מצב צפוי).setRating throws IllegalArgumentException (a bug in the caller), and find throws a checked NotFoundException (an expected situation).

עוטפים עם הקשרWrapping with context

  • sumYears סוכמת שנים משורות Title;Year.sumYears sums years from Title;Year lines.

מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException

  • BookNotFoundException (checked) שומרת את הכותר המבוקש ובונה הודעה.BookNotFoundException (checked) keeps the requested title and builds a message.

חריגות מודחקותSuppressed exceptions

  • הגוף של try-with-resources זורק body failed, וגם close() זורק close failed.The body of a try-with-resources throws body failed, and close() throws close failed too.

multi-catch ו-finallymulti-catch and finally

  • risky(s) מחזירה 100 / parseInt(s).risky(s) returns 100 / parseInt(s).

מה למדנוWhat we learned

  • חריגה checked: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException.checked exception: An exception extending Exception (not RuntimeException), like IOException.
  • load מכריזה throws IOException.load declares throws IOException.
  • InvalidYearException היא checked.InvalidYearException is checked.
  • שני משאבים נפתחים, הגוף זורק חריגה, ובכל זאת שניהם נסגרים, בסדר הפוך, ורק אחר כך ה-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

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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