חלק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.
הנקודות החשובות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 atry. - כשנזרקת חריגה, Java קופצת ל-
catchהמתאים, ואחריו התוכנית ממשיכה.When an exception is thrown, Java jumps to the matchingcatch, and then the program goes on. 10 / 0זורק ArithmeticException.10 / 0throws 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 areturn. 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 whenInteger.parseIntorDouble.parseDoubleget 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 areturn. 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 whenInteger.parseIntorDouble.parseDoubleget 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 catches | 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. |
ArithmeticException | ממוצע של כלוםAverage of nothing | ArithmeticException: / 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). |