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

JavaJava
12
חלקPart 2: מתודות ומערכיםMethods & arrays כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

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

מה זו חריגה, try, catch ו-finally, זריקה עם throw, והודעות שגיאה שעוזרות.

What an exception is, try, catch and finally, throwing with throw, and error messages that help.

או Ctrl+Por Ctrl+P

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

  • try ו-catch: `try { ...try and catch: `try { ...
  • finally: בלוק שרץ אחרי try/catch תמיד:finally: A block that runs after try/catch always:
  • 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.
  • 10 / 0 זורק ArithmeticException.10 / 0 throws an ArithmeticException.
  • השורה הבאה ב-try מדולגת, ה-catch רץ, ואז finally.The next line in the try is skipped, the catch runs, then finally.
  • מתודה שמקבלת ערך לא הגיוני זורקת IllegalArgumentException עם הודעה ברורה: מה מותר ומה התקבל.A method that gets a nonsense value throws an IllegalArgumentException with a clear message: what's allowed and what came in.

מונחיםTerms

  • חריגה (exception)exception: בעיה שקורית בזמן ריצה, למשל חלוקה ב-0. אם אף אחד לא מטפל בה, התוכנית עוצרת ומדפיסה Exception in thread "main".A problem that happens while running, like dividing by 0. If nobody handles it, the program stops and prints Exception in thread "main".
  • try ו-catchtry and catch: try { ... } catch (SomeException e) { ... }: אם בתוך ה-try נזרקת חריגה מהסוג הזה, קופצים ל-catch במקום לקרוס. השורות שאחרי מקום החריגה ב-try לא רצות.try { ... } catch (SomeException e) { ... }: if an exception of that type is thrown inside the try, jump to the catch instead of crashing. The lines after the throw point in the try don't run.
  • finallyfinally: בלוק שרץ אחרי try/catch תמיד: גם כשהכול עבר, גם כשנתפסה חריגה, ואפילו כשיש return. מתאים לסגירת משאבים.A block that runs after try/catch always: when all went well, when an exception was caught, even with a return. Good for closing resources.
  • throwthrow: זורק חריגה בעצמכם: throw new IllegalArgumentException("...");. המתודה נעצרת מיד, והחריגה עולה למי שקרא לה.Throws an exception yourself: throw new IllegalArgumentException("...");. The method stops at once, and the exception goes up to its caller.
  • NumberFormatExceptionNumberFormatException: נזרקת כש-Integer.parseInt או Double.parseDouble מקבלות טקסט שאינו מספר: For input string: "12a".Thrown when Integer.parseInt or Double.parseDouble get text that isn't a number: For input string: "12a".
  • IllegalArgumentExceptionIllegalArgumentException: החריגה המקובלת כשמתודה מקבלת ערך לא חוקי. ההודעה צריכה לומר מה צפוי ומה התקבל.The usual exception when a method gets an illegal value. The message should say what was expected and what came in.
  • try ו-catchtry and catch: try { ... } catch (SomeException e) { ... }: אם בתוך ה-try נזרקת חריגה מהסוג הזה, קופצים ל-catch במקום לקרוס. השורות שאחרי מקום החריגה ב-try לא רצות.try { ... } catch (SomeException e) { ... }: if an exception of that type is thrown inside the try, jump to the catch instead of crashing. The lines after the throw point in the try don't run.
  • finallyfinally: בלוק שרץ אחרי try/catch תמיד: גם כשהכול עבר, גם כשנתפסה חריגה, ואפילו כשיש return. מתאים לסגירת משאבים.A block that runs after try/catch always: when all went well, when an exception was caught, even with a return. Good for closing resources.
  • throwthrow: זורק חריגה בעצמכם: throw new IllegalArgumentException("...");. המתודה נעצרת מיד, והחריגה עולה למי שקרא לה.Throws an exception yourself: throw new IllegalArgumentException("...");. The method stops at once, and the exception goes up to its caller.
  • NumberFormatExceptionNumberFormatException: נזרקת כש-Integer.parseInt או Double.parseDouble מקבלות טקסט שאינו מספר: For input string: "12a".Thrown when Integer.parseInt or Double.parseDouble get text that isn't a number: For input string: "12a".
  • IllegalArgumentExceptionIllegalArgumentException: החריגה המקובלת כשמתודה מקבלת ערך לא חוקי. ההודעה צריכה לומר מה צפוי ומה התקבל.The usual exception when a method gets an illegal value. The message should say what was expected and what came in.

Cheatsheet

try ו-catch: ממשיכים לרוץtry and catch: keep running
String[] inputs = {"21", "12a"};
for (String s : inputs) {
    try {
        int n = Integer.parseInt(s);
        System.out.println(s + " -> " + n * 2);
    } catch (NumberFormatException e) {
        System.out.println(s + " is not a number");
    }
}
System.out.println("Still running");
finally רץ תמידfinally always runs
try {
    System.out.println("Opening");
    int x = 10 / 0;
    System.out.println("Never printed");
} catch (ArithmeticException e) {
    System.out.println("Caught: " + e.getMessage());
} finally {
    System.out.println("Closing");
}
throw: אתם מחליטים מה לא חוקיthrow: you decide what's illegal
setYear(1965);
try {
    setYear(3000);
} catch (IllegalArgumentException e) {
    System.out.println("Error: " + e.getMessage());
}

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

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
NumberFormatExceptionחריגה שאף אחד לא תופסAn exception nobody catchesNumberFormatException: 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.
ArithmeticExceptionממוצע של כלוםAverage of nothingArithmeticException: / by zero בשורה 8: grades.length הוא 0. בשלמים, חילוק ב-0 זורק חריגה (ב-double הוא היה נותן NaN).ArithmeticException: / by zero on line 8: grades.length is 0. With ints, dividing by 0 throws (with doubles it would give NaN).

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