נבנה על ידי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.

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 a return. 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 when Integer.parseInt or Double.parseDouble get 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.

טעות נפוצהCommon mistake

חריגה שאף אחד לא תופס

An exception nobody catches

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("Start");
        int n = Integer.parseInt("12a");
        System.out.println(n * 2);
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
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)
בעברית פשוטה: In plain words: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

Main.java
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");
    }
}
פלטOutput
21 -> 42
12a is not a number
Still running
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

Main.java
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");
        }
    }
}
פלטOutput
Opening
Caught: / by zero
Closing
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

Main.java
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());
        }
    }
}
פלטOutput
Year set: 1965
Error: Year must be 0-2026, got 3000
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

טעות נפוצהCommon mistake

ממוצע של כלום

Average of nothing

Main.java
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);
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:8)
בעברית פשוטה: In plain words: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

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.

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