חריגות בסיסיותBasic exceptions
מה זו חריגה, try, catch ו-finally, זריקה עם throw, והודעות שגיאה שעוזרות.
What an exception is, try, catch and finally, throwing with throw, and error messages that help.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- try ו-catch:
try { ... } catch (SomeException e) { ... }: אם בתוך ה-try נזרקת חריגה מהסוג הזה, קופצים ל-catch במקום לקרוס. השורות שאחרי מקום החריגה ב-try לא רצות.try and catch: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. - finally: בלוק שרץ אחרי try/catch תמיד: גם כשהכול עבר, גם כשנתפסה חריגה, ואפילו כשיש
return. מתאים לסגירת משאבים.finally: A block that runs after try/catch always: when all went well, when an exception was caught, even with areturn. Good for closing resources. - throw: זורק חריגה בעצמכם:
throw new IllegalArgumentException("...");. המתודה נעצרת מיד, והחריגה עולה למי שקרא לה.throw: Throws an exception yourself:throw new IllegalArgumentException("...");. The method stops at once, and the exception goes up to its caller. - NumberFormatException: נזרקת כש-
Integer.parseIntאוDouble.parseDoubleמקבלות טקסט שאינו מספר:For input string: "12a".NumberFormatException: Thrown whenInteger.parseIntorDouble.parseDoubleget text that isn't a number:For input string: "12a". - IllegalArgumentException: החריגה המקובלת כשמתודה מקבלת ערך לא חוקי. ההודעה צריכה לומר מה צפוי ומה התקבל.IllegalArgumentException: The usual exception when a method gets an illegal value. The message should say what was expected and what came in.
02חריגה שאף אחד לא תופסAn exception nobody catches
Integer.parseInt("12a") זורקת NumberFormatException. אף אחד לא תופס אותה, ולכן התוכנית נעצרת, Java מדפיסה stack trace, והשורה האחרונה לא רצה.
Integer.parseInt("12a") throws a NumberFormatException. Nobody catches it, so the program stops, Java prints a stack trace, and the last line never runs.
חריגה שאף אחד לא תופס
An exception nobody catches
public class Main {
public static void main(String[] args) {
System.out.println("Start");
int n = Integer.parseInt("12a");
System.out.println(n * 2);
}
}Start Exception in thread "main" java.lang.NumberFormatException: For input string: "12a" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:662) at java.base/java.lang.Integer.parseInt(Integer.java:778) at Main.main(Main.java:4)
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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03try ו-catch: ממשיכים לרוץtry and catch: keep running
עוטפים את מה שעלול להיכשל ב-try. כשנזרקת חריגה, Java קופצת ל-catch המתאים, ואחריו התוכנית ממשיכה. בסימולציה רואים את הקפיצה: השורה שאחרי parseInt לא רצה בפעם השנייה.
Wrap what might fail in a try. When an exception is thrown, Java jumps to the matching catch, and then the program goes on. In the simulation you see the jump: the line after parseInt doesn't run the second time.
public class Main {
public static void main(String[] args) {
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");
}
}21 -> 42 12a is not a number Still running
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04finally רץ תמידfinally always runs
10 / 0 זורק ArithmeticException. השורה הבאה ב-try מדולגת, ה-catch רץ, ואז finally. e.getMessage() נותן את ההודעה בלי שם החריגה.
10 / 0 throws an ArithmeticException. The next line in the try is skipped, the catch runs, then finally. e.getMessage() gives the message without the exception's name.
public class Main {
public static void main(String[] args) {
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");
}
}
}Opening Caught: / by zero Closing
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05throw: אתם מחליטים מה לא חוקי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.
public class Main {
static void setYear(int year) {
if (year < 0 || year > 2026) {
throw new IllegalArgumentException("Year must be 0-2026, got " + year);
}
System.out.println("Year set: " + year);
}
public static void main(String[] args) {
setYear(1965);
try {
setYear(3000);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Year set: 1965 Error: Year must be 0-2026, got 3000
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.
These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.
ממוצע של כלום
Average of nothing
public class Main {
public static void main(String[] args) {
int[] grades = {};
int sum = 0;
for (int g : grades) {
sum += g;
}
System.out.println("Average: " + sum / grades.length);
}
}Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:8)
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).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07הצעד של היום בפרויקט מדףToday's step in the Shelf project
שורות בפורמט Title;Year: Dune;1965, Emma;18x5, Ulysses;1922. הדפיסו כל ספר תקין כמו Dune (1965). על שנה לא חוקית הדפיסו Skipping Emma: bad year 18x5 והמשיכו. בסוף Valid books: 2.
Lines as Title;Year: Dune;1965, Emma;18x5, Ulysses;1922. Print each valid book like Dune (1965). For an illegal year print Skipping Emma: bad year 18x5 and go on. Finally Valid books: 2.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.