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

חזרה למפגשBack
JavaJava

חריגות בסיסיותBasic exceptions

מפגש 12: מה זו חריגה, try, catch ו-finally, זריקה עם throw, והודעות שגיאה שעוזרות.Session 12: What an exception is, try, catch and finally, throwing with throw, and error messages that help.

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

  • מונחיםTerms
  • חריגה שאף אחד לא תופסAn exception nobody catches
  • try ו-catch: ממשיכים לרוץtry and catch: keep running
  • finally רץ תמידfinally always runs
  • throw: אתם מחליטים מה לא חוקיthrow: you decide what's illegal
  • טעויות נפוצותCommon mistakes
נושאTopic 1

מונחיםTerms

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

  • try ו-catch: `try { ...try and catch: `try { ...
  • finally: בלוק שרץ אחרי try/catch תמיד:finally: A block that runs after try/catch always:
  • throw: זורק חריגה בעצמכם:throw: Throws an exception yourself:
  • NumberFormatException: נזרקת כש-Integer.parseInt או Double.parseDouble מקבלות טקסט שאינו מספר:NumberFormatException: Thrown when Integer.parseInt or Double.parseDouble get text that isn't a number:
  • IllegalArgumentException: החריגה המקובלת כשמתודה מקבלת ערך לא חוקי.IllegalArgumentException: The usual exception when a method gets an illegal value.
נושאTopic 2

חריגה שאף אחד לא תופסAn exception nobody catches

חריגה שאף אחד לא תופסAn exception nobody catches

  • Integer.parseInt("12a") זורקת NumberFormatException.Integer.parseInt("12a") throws a NumberFormatException.
  • אף אחד לא תופס אותה, ולכן התוכנית נעצרת, Java מדפיסה stack trace, והשורה האחרונה לא רצה.Nobody catches it, so the program stops, Java prints a stack trace, and the last line never runs.

טעות נפוצהCommon mistake

Main.java · main
System.out.println("Start");
int n = Integer.parseInt("12a");
System.out.println(n * 2);
מה Java עונהWhat Java says
Exception in thread "main" java.lang.NumberFormatException: For input string: "12a"
NumberFormatException: For input string: "12a" בשורה 4. Start כבר הודפס, אבל n * 2 לא.NumberFormatException: For input string: "12a" on line 4. Start was already printed, but n * 2 never is.
נושאTopic 3

try ו-catch: ממשיכים לרוץtry and catch: keep running

try ו-catch: ממשיכים לרוץtry and catch: keep running

  • עוטפים את מה שעלול להיכשל ב-try.Wrap what might fail in a try.
  • כשנזרקת חריגה, Java קופצת ל-catch המתאים, ואחריו התוכנית ממשיכה.When an exception is thrown, Java jumps to the matching catch, and then the program goes on.
  • בסימולציה רואים את הקפיצה: השורה שאחרי parseInt לא רצה בפעם השנייה.In the simulation you see the jump: the line after parseInt doesn't run the second time.
נושאTopic 4

finally רץ תמידfinally always runs

finally רץ תמידfinally always runs

  • 10 / 0 זורק ArithmeticException.10 / 0 throws an ArithmeticException.
  • השורה הבאה ב-try מדולגת, ה-catch רץ, ואז finally.The next line in the try is skipped, the catch runs, then finally.
  • e.getMessage() נותן את ההודעה בלי שם החריגה.e.getMessage() gives the message without the exception's name.
נושאTopic 5

throw: אתם מחליטים מה לא חוקיthrow: you decide what's illegal

throw: אתם מחליטים מה לא חוקיthrow: you decide what's illegal

  • מתודה שמקבלת ערך לא הגיוני זורקת IllegalArgumentException עם הודעה ברורה: מה מותר ומה התקבל.A method that gets a nonsense value throws an IllegalArgumentException with a clear message: what's allowed and what came in.
  • מי שקורא למתודה מחליט אם לתפוס.The caller decides whether to catch it.
נושאTopic 6

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

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

  • `ArithmeticException:`ArithmeticException:
נושאTopic 7

פרויקט מדףShelf project

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

  • מדף, צעד 12: שנה לא חוקית לא מפילהShelf, step 12: a bad year doesn't crash

try ו-catch: `try { ...try and catch: `try { ...

finally: בלוק שרץ אחרי try/catch תמיד:finally: A block that runs after try/catch always:

throw: זורק חריגה בעצמכם:throw: Throws an exception yourself:

NumberFormatException: נזרקת כש-Integer.parseInt או Double.parseDouble מקבלות טקסט שאינו מספר:NumberFormatException: Thrown when Integer.parseInt or Double.parseDouble get text that isn't a number:

IllegalArgumentException: החריגה המקובלת כשמתודה מקבלת ערך לא חוקי.IllegalArgumentException: The usual exception when a method gets an illegal value.

Integer.parseInt("12a") זורקת NumberFormatException.Integer.parseInt("12a") throws a NumberFormatException.

אף אחד לא תופס אותה, ולכן התוכנית נעצרת, Java מדפיסה stack trace, והשורה האחרונה לא רצה.Nobody catches it, so the program stops, Java prints a stack trace, and the last line never runs.

עוטפים את מה שעלול להיכשל ב-try.Wrap what might fail in a try.

כשנזרקת חריגה, Java קופצת ל-catch המתאים, ואחריו התוכנית ממשיכה.When an exception is thrown, Java jumps to the matching catch, and then the program goes on.

בסימולציה רואים את הקפיצה: השורה שאחרי parseInt לא רצה בפעם השנייה.In the simulation you see the jump: the line after parseInt doesn't run the second time.

10 / 0 זורק ArithmeticException.10 / 0 throws an ArithmeticException.

השורה הבאה ב-try מדולגת, ה-catch רץ, ואז finally.The next line in the try is skipped, the catch runs, then finally.

e.getMessage() נותן את ההודעה בלי שם החריגה.e.getMessage() gives the message without the exception's name.

מתודה שמקבלת ערך לא הגיוני זורקת IllegalArgumentException עם הודעה ברורה: מה מותר ומה התקבל.A method that gets a nonsense value throws an IllegalArgumentException with a clear message: what's allowed and what came in.

מי שקורא למתודה מחליט אם לתפוס.The caller decides whether to catch it.

`ArithmeticException:`ArithmeticException:

מדף, צעד 12: שנה לא חוקית לא מפילהShelf, step 12: a bad year doesn't crash

מה ידפיס הקוד?What does it print?

  • A B C DA B C D
  • A C DA C D
  • A CA C
  • A ואז קריסהA then a crash

A C DA C D

מתי רץ בלוק finally?When does a finally block run?

  • רק כשנזרקה חריגהOnly when an exception was thrown
  • רק כשלא נזרקה חריגהOnly when no exception was thrown
  • תמידAlways
  • אף פעם, אם יש catchNever, if there's a catch

תמידAlways

איזו שורה זורקת חריגה?Which line throws an exception?

  • throw new IllegalArgumentException("bad");throw new IllegalArgumentException("bad");
  • return new IllegalArgumentException("bad");return new IllegalArgumentException("bad");
  • throws IllegalArgumentException("bad");throws IllegalArgumentException("bad");
  • catch ("bad");catch ("bad");

throw new IllegalArgumentException("bad");throw new IllegalArgumentException("bad");

המרה עם ברירת מחדלParse with a fallback

  • כתבו static int parseOr(String s, int fallback) שמחזירה את המספר, או את fallback אם הטקסט אינו מספר.Write static int parseOr(String s, int fallback) returning the number, or fallback if the text isn't a number.

ממוצע של כלוםAverage of nothing

  • עם מערך ציונים ריק התוכנית קורסת.With an empty grades array the program crashes.

גיל לא חוקיAn illegal age

  • כתבו static void checkAge(int age) שזורקת `IllegalArgumentException("Bad age:Write static void checkAge(int age) that throws `IllegalArgumentException("Bad age:

הסדר של finallyThe order of finally

  • הדפיסו start, ואז ב-try המירו את "x" למספר (והדפיסו parsed אחרי ההמרה).Print start, then in a try convert "x" to a number (printing parsed after the conversion).

מה למדנוWhat we learned

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

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

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