נבנה על ידיBuilt by Ariel Yohimovich
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.
היררכיית החריגות, throws, חריגות משלכם, ו-try-with-resources שסוגר משאבים לבד. בסוף המפגש מוסיפים צעד לפרויקט המלווה.The exception hierarchy, throws, your own exceptions, and try-with-resources that closes resources by itself. At the end we add a step to the companion project.מה נעשה היום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
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגש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()) { ...
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושא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.
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.נושא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.
InvalidYearException היא checked. parseYear הופכת את ה-NumberFormatException הטכני להודעה שמבינים, ושומרת אותו כ-cause.InvalidYearException is checked. 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.
שני משאבים נפתחים, הגוף זורק חריגה, ובכל זאת שניהם נסגרים, בסדר הפוך, ורק אחר כך ה-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:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.נושאTopic 6
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException
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).חריגה checked: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException.checked exception: An exception extending Exception (not RuntimeException), like IOException.
המונחים של המפגשThis session's termsחריגה unchecked: חריגה שיורשת מ-RuntimeException (IllegalArgumentException, NullPointerException).unchecked exception: An exception extending RuntimeException (IllegalArgumentException, NullPointerException).
המונחים של המפגשThis session's termsthrows: static String load(...) throws IOException:throws: static String load(...) throws IOException:
המונחים של המפגשThis session's termsחריגה משלכם: class BookNotFoundException extends Exception:custom exception: class BookNotFoundException extends Exception:
המונחים של המפגשThis session's termsסיבה (cause): new DataException("line 2 bad", e) עוטף את החריגה המקורית.cause: new DataException("line 2 bad", e) wraps the original exception.
המונחים של המפגשThis session's termstry-with-resources: `try (Res r = new Res()) { ...try-with-resources: `try (Res r = new Res()) { ...
המונחים של המפגשThis session's termsload מכריזה throws IOException.load declares throws IOException.
checked: javac מחייב לטפלchecked: javac forces you to handle itmain קורא לה בלי try ובלי throws, ו-javac לא מקמפל.main calls it with no try and no throws, and javac won't compile.
checked: javac מחייב לטפלchecked: javac forces you to handle itInvalidYearException היא checked.InvalidYearException is checked.
חריגה משלכם, עם סיבהYour own exception, with a causeparseYear הופכת את ה-NumberFormatException הטכני להודעה שמבינים, ושומרת אותו כ-cause.parseYear turns the technical NumberFormatException into a message people understand, and keeps it as the cause.
חריגה משלכם, עם סיבהYour own exception, with a causeשני משאבים נפתחים, הגוף זורק חריגה, ובכל זאת שניהם נסגרים, בסדר הפוך, ורק אחר כך ה-catch רץ.Two resources open, the body throws, and still both close, in reverse order, and only then does the catch run.
try-with-resourcestry-with-resourcesunreported exception IOException; must be caught or declared to be thrown:unreported exception IOException; must be caught or declared to be thrown:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException
הצעד של היום בפרויקט מדףToday's step in the Shelf projectאיזו מהבאות checked?Which of these is checked?
IOExceptionIOExceptionNullPointerExceptionNullPointerExceptionIllegalArgumentExceptionIllegalArgumentExceptionArithmeticExceptionArithmeticException
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.IOExceptionIOException
נכון: יורשת מ-Exception ולא מ-RuntimeException.Right: it extends Exception, not RuntimeException.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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.b ואז ab then a
נכון: הפוך לסדר הפתיחה.Right: reverse of opening.מתודה מקבלת דירוג 9 כשמותר 1–5. מה לזרוק?A method gets a rating of 9 when 1–5 is allowed. What should it throw?
IllegalArgumentException (unchecked)IllegalArgumentException (unchecked)IOExceptionIOExceptionExceptionException- כלום, להחזיר -1Nothing, return -1
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.IllegalArgumentException (unchecked)IllegalArgumentException (unchecked)
נכון: זה באג אצל מי שקרא.Right: it's a bug in the caller.שנה לא חוקיתAn invalid year
- כתבו את
InvalidYearException (checked, עם בנאי להודעה ובנאי להודעה וסיבה) ואת parseYear מהתזכורת.Write InvalidYearException (checked, with a message constructor and a message-and-cause constructor) and parseYear from the refresher.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: unreported exceptionBug hunter: unreported exception
- התוכנית מהתזכורת לא מתקמפלת.The program from the refresher doesn't compile.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.סדר הסגירהThe closing order
- משאב
Res implements AutoCloseable מדפיס open ו-close.A resource Res implements AutoCloseable prints open and close.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מתי 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).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.עוטפים עם הקשרWrapping with context
sumYears סוכמת שנים משורות Title;Year.sumYears sums years from Title;Year lines.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException
BookNotFoundException (checked) שומרת את הכותר המבוקש ובונה הודעה.BookNotFoundException (checked) keeps the requested title and builds a message.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.חריגות מודחקות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.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.multi-catch ו-finallymulti-catch and finally
risky(s) מחזירה 100 / parseInt(s).risky(s) returns 100 / parseInt(s).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנו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
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.