חריגות בסיסיותBasic exceptions
מה זו חריגה, try, catch ו-finally, זריקה עם throw, והודעות שגיאה שעוזרות.
What an exception is, try, catch and finally, throwing with throw, and error messages that help.
המרה עם ברירת מחדלParse with a fallback
תזכורת: מה ביקשוReminder: the task
כתבו static int parseOr(String s, int fallback) שמחזירה את המספר, או את fallback אם הטקסט אינו מספר. הדפיסו parseOr("42", 0) + " " + parseOr("4x", -1): 42 -1.
Write static int parseOr(String s, int fallback) returning the number, or fallback if the text isn't a number. Print parseOr("42", 0) + " " + parseOr("4x", -1): 42 -1.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int parseOr(String s, int fallback) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return fallback;
}
}
public static void main(String[] args) {
System.out.println(parseOr("42", 0) + " " + parseOr("4x", -1));
}
}42 -1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ממוצע של כלוםAverage of nothing
תזכורת: מה ביקשוReminder: the task
עם מערך ציונים ריק התוכנית קורסת. צפו ב"איפה זה נשבר", ועטפו את החילוק ב-try/catch כך שיודפס No grades.
With an empty grades array the program crashes. Watch "where it breaks", and wrap the division in try/catch so it prints No grades.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
int[] grades = {};
int sum = 0;
for (int g : grades) {
sum += g;
}
try {
System.out.println("Average: " + sum / grades.length);
} catch (ArithmeticException e) {
System.out.println("No grades");
}
}
}No grades
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
גיל לא חוקיAn illegal age
תזכורת: מה ביקשוReminder: the task
כתבו static void checkAge(int age) שזורקת IllegalArgumentException("Bad age: " + age) כשהגיל מחוץ ל-0 עד 120. ב-main, בתוך try: בדקו 30 (הדפיסו 30 is fine), ואז -3. ב-catch הדפיסו Error: ואת ההודעה.
Write static void checkAge(int age) that throws IllegalArgumentException("Bad age: " + age) when the age is outside 0 to 120. In main, inside a try: check 30 (print 30 is fine), then -3. In the catch print Error: and the message.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static void checkAge(int age) {
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Bad age: " + age);
}
}
public static void main(String[] args) {
try {
checkAge(30);
System.out.println("30 is fine");
checkAge(-3);
System.out.println("Never printed");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}30 is fine Error: Bad age: -3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הסדר של finallyThe order of finally
תזכורת: מה ביקשוReminder: the task
הדפיסו start, ואז ב-try המירו את "x" למספר (והדפיסו parsed אחרי ההמרה). ב-catch הדפיסו bad, וב-finally done. הפלט: start, bad, done.
Print start, then in a try convert "x" to a number (printing parsed after the conversion). In the catch print bad, and in the finally done. The output: start, bad, done.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
System.out.println("start");
try {
Integer.parseInt("x");
System.out.println("parsed");
} catch (NumberFormatException e) {
System.out.println("bad");
} finally {
System.out.println("done");
}
}
}start bad done
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שואלים עד שמקבלים מספרAsk until you get a number
תזכורת: מה ביקשוReminder: the task
קראו שורות מהקלט עד שמגיע מספר. על כל שורה שאינה מספר הדפיסו Not a number: ..., ועל המספר Got ... וסיימו. עם הקלט abc ואז 12 יודפס Not a number: abc ואז Got 12.
Read input lines until a number arrives. For every line that isn't a number print Not a number: ..., and for the number print Got ... and stop. With the input abc then 12 it prints Not a number: abc then Got 12.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
String line = in.nextLine();
try {
int n = Integer.parseInt(line);
System.out.println("Got " + n);
break;
} catch (NumberFormatException e) {
System.out.println("Not a number: " + line);
}
}
}
}abc Not a number: abc 12 Got 12
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 12: שנה לא חוקית לא מפילהShelf, step 12: a bad year doesn't crash
תזכורת: מה ביקשוReminder: the task
שורות בפורמט 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.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
String[] lines = {"Dune;1965", "Emma;18x5", "Ulysses;1922"};
int valid = 0;
for (String line : lines) {
String[] parts = line.split(";");
try {
int year = Integer.parseInt(parts[1]);
System.out.println(parts[0] + " (" + year + ")");
valid++;
} catch (NumberFormatException e) {
System.out.println("Skipping " + parts[0] + ": bad year " + parts[1]);
}
}
System.out.println("Valid books: " + valid);
}
}Dune (1965) Skipping Emma: bad year 18x5 Ulysses (1922) Valid books: 2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שני catchTwo catches
תזכורת: מה ביקשוReminder: the task
כתבו static String safeGet(int[] a, String index) שממירה את האינדקס ומחזירה את הערך כמחרוזת. אם האינדקס אינו מספר: not a number; אם הוא מחוץ למערך: bad index. עבור {10, 20, 30} עם "1", "9", "x": 20, bad index, not a number.
Write static String safeGet(int[] a, String index) converting the index and returning the value as a string. If the index isn't a number: not a number; if it's outside the array: bad index. For {10, 20, 30} with "1", "9", "x": 20, bad index, not a number.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static String safeGet(int[] a, String index) {
try {
return "" + a[Integer.parseInt(index)];
} catch (NumberFormatException e) {
return "not a number";
} catch (ArrayIndexOutOfBoundsException e) {
return "bad index";
}
}
public static void main(String[] args) {
int[] a = {10, 20, 30};
System.out.println(safeGet(a, "1"));
System.out.println(safeGet(a, "9"));
System.out.println(safeGet(a, "x"));
}
}20 bad index not a number
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הודעות שגיאה שעוזרותError messages that help
תזכורת: מה ביקשוReminder: the task
כתבו static int minutes(String time) שממירה HH:MM לדקות מתחילת היום. אם אין בדיוק נקודתיים אחד, זרקו Bad time: 7 (use HH:MM). אם השעה מחוץ ל-0 עד 23, זרקו Bad time: 25:00 (hour must be 0-23). עבור 09:30, 25:00, 7 הדפיסו את הדקות, או Error: ואת ההודעה: 570, Error: Bad time: 25:00 (hour must be 0-23), Error: Bad time: 7 (use HH:MM).
Write static int minutes(String time) converting HH:MM to minutes since midnight. Without exactly one colon, throw Bad time: 7 (use HH:MM). With an hour outside 0 to 23, throw Bad time: 25:00 (hour must be 0-23). For 09:30, 25:00, 7 print the minutes, or Error: and the message: 570, Error: Bad time: 25:00 (hour must be 0-23), Error: Bad time: 7 (use HH:MM).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int minutes(String time) {
String[] parts = time.split(":");
if (parts.length != 2) {
throw new IllegalArgumentException("Bad time: " + time + " (use HH:MM)");
}
int h = Integer.parseInt(parts[0]);
int m = Integer.parseInt(parts[1]);
if (h < 0 || h > 23) {
throw new IllegalArgumentException("Bad time: " + time + " (hour must be 0-23)");
}
return h * 60 + m;
}
public static void main(String[] args) {
for (String t : new String[]{"09:30", "25:00", "7"}) {
try {
System.out.println(minutes(t));
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}570 Error: Bad time: 25:00 (hour must be 0-23) Error: Bad time: 7 (use HH:MM)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.