חריגות checked מול unchecked ו-try-with-resourcesChecked vs unchecked exceptions & try-with-resources
היררכיית החריגות, throws, חריגות משלכם, ו-try-with-resources שסוגר משאבים לבד.
The exception hierarchy, throws, your own exceptions, and try-with-resources that closes resources by itself.
שנה לא חוקיתAn invalid year
תזכורת: מה ביקשוReminder: the task
כתבו את InvalidYearException (checked, עם בנאי להודעה ובנאי להודעה וסיבה) ואת parseYear מהתזכורת. עבור 1965, 3000, 19x5 הדפיסו:
ok 1965 / bad: year out of range: 3000 / bad: not a year: 19x5 (cause: NumberFormatException).
Write InvalidYearException (checked, with a message constructor and a message-and-cause constructor) and parseYear from the refresher. For 1965, 3000, 19x5 print:
ok 1965 / bad: year out of range: 3000 / bad: not a year: 19x5 (cause: NumberFormatException).
סימולציה: הפתרון רץ שורה אחרי שורה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 parseYear(String text) throws InvalidYearException {
try {
int y = Integer.parseInt(text);
if (y < 0 || y > 2026) {
throw new InvalidYearException("year out of range: " + y);
}
return y;
} catch (NumberFormatException e) {
throw new InvalidYearException("not a year: " + text, e);
}
}
public static void main(String[] args) {
for (String t : new String[]{"1965", "3000", "19x5"}) {
try {
System.out.println("ok " + parseYear(t));
} catch (InvalidYearException e) {
System.out.println("bad: " + e.getMessage() + (e.getCause() != null ? " (cause: " + e.getCause().getClass().getSimpleName() + ")" : ""));
}
}
}
}
class InvalidYearException extends Exception {
InvalidYearException(String message) {
super(message);
}
InvalidYearException(String message, Throwable cause) {
super(message, cause);
}
}ok 1965 bad: year out of range: 3000 bad: not a year: 19x5 (cause: NumberFormatException)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: unreported exceptionBug hunter: unreported exception
תזכורת: מה ביקשוReminder: the task
התוכנית מהתזכורת לא מתקמפלת. תפסו את ה-IOException ב-main, טענו גם "", והדפיסו data of shelf.txt ואז could not load: no file name.
The program from the refresher doesn't compile. Catch the IOException in main, load "" too, and print data of shelf.txt then could not load: no file name.
סימולציה: הפתרון רץ שורה אחרי שורה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
import java.io.IOException;
public class Main {
static String load(String name) throws IOException {
if (name.isEmpty()) {
throw new IOException("no file name");
}
return "data of " + name;
}
public static void main(String[] args) {
try {
System.out.println(load("shelf.txt"));
System.out.println(load(""));
} catch (IOException e) {
System.out.println("could not load: " + e.getMessage());
}
}
}data of shelf.txt could not load: no file name
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
סדר הסגירהThe closing order
תזכורת: מה ביקשוReminder: the task
משאב Res implements AutoCloseable מדפיס open ו-close. פתחו db ו-file ב-try-with-resources אחד, הדפיסו working with db and file, ואחרי הבלוק done. הפלט: open db, open file, working with db and file, close file, close db, done.
A resource Res implements AutoCloseable prints open and close. Open db and file in one try-with-resources, print working with db and file, and after the block done. The output: open db, open file, working with db and file, close file, close db, 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) {
try (Res a = new Res("db"); Res b = new Res("file")) {
System.out.println("working with " + a.name() + " and " + b.name());
}
System.out.println("done");
}
}
class Res implements AutoCloseable {
private final String name;
Res(String name) {
this.name = name;
System.out.println("open " + name);
}
String name() {
return name;
}
@Override
public void close() {
System.out.println("close " + name);
}
}open db open file working with db and file close file close db done
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מתי checked ומתי uncheckedWhen checked, when unchecked
תזכורת: מה ביקשוReminder: the task
setRating זורקת IllegalArgumentException (באג אצל מי שקרא), ו-find זורקת NotFoundException checked (מצב צפוי). הדפיסו:
rating 4 / bug in the caller: rating must be 1-5, got 9 / Dune by Herbert / expected situation: no book called Hamlet.
setRating throws IllegalArgumentException (a bug in the caller), and find throws a checked NotFoundException (an expected situation). Print:
rating 4 / bug in the caller: rating must be 1-5, got 9 / Dune by Herbert / expected situation: no book called Hamlet.
סימולציה: הפתרון רץ שורה אחרי שורה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 setRating(int r) {
if (r < 1 || r > 5) {
throw new IllegalArgumentException("rating must be 1-5, got " + r);
}
System.out.println("rating " + r);
}
static String find(String title) throws NotFoundException {
if (!title.equals("Dune")) {
throw new NotFoundException("no book called " + title);
}
return "Dune by Herbert";
}
public static void main(String[] args) {
setRating(4);
try {
setRating(9);
} catch (IllegalArgumentException e) {
System.out.println("bug in the caller: " + e.getMessage());
}
try {
System.out.println(find("Dune"));
System.out.println(find("Hamlet"));
} catch (NotFoundException e) {
System.out.println("expected situation: " + e.getMessage());
}
}
}
class NotFoundException extends Exception {
NotFoundException(String message) {
super(message);
}
}rating 4 bug in the caller: rating must be 1-5, got 9 Dune by Herbert expected situation: no book called Hamlet
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עוטפים עם הקשרWrapping with context
תזכורת: מה ביקשוReminder: the task
sumYears סוכמת שנים משורות Title;Year. על שורה פגומה היא זורקת DataException עם מספר השורה והסיבה המקורית (multi-catch של NumberFormatException | ArrayIndexOutOfBoundsException). הדפיסו 3780 ואז line 2: bad record 'Emma' <- ArrayIndexOutOfBoundsException.
sumYears sums years from Title;Year lines. On a broken line it throws a DataException with the line number and the original cause (a multi-catch of NumberFormatException | ArrayIndexOutOfBoundsException). Print 3780 then line 2: bad record 'Emma' <- ArrayIndexOutOfBoundsException.
סימולציה: הפתרון רץ שורה אחרי שורה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.List;
public class Main {
static int sumYears(List<String> lines) throws DataException {
int sum = 0;
for (int i = 0; i < lines.size(); i++) {
try {
sum += Integer.parseInt(lines.get(i).split(";")[1]);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
throw new DataException("line " + (i + 1) + ": bad record '" + lines.get(i) + "'", e);
}
}
return sum;
}
public static void main(String[] args) {
try {
System.out.println(sumYears(List.of("Dune;1965", "Emma;1815")));
System.out.println(sumYears(List.of("Dune;1965", "Emma")));
} catch (DataException e) {
System.out.println(e.getMessage() + " <- " + e.getCause().getClass().getSimpleName());
}
}
}
class DataException extends Exception {
DataException(String message, Throwable cause) {
super(message, cause);
}
}3780 line 2: bad record 'Emma' <- ArrayIndexOutOfBoundsException
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException
תזכורת: מה ביקשוReminder: the task
BookNotFoundException (checked) שומרת את הכותר המבוקש ובונה הודעה. Shelf.find מחזירה ספר או זורקת. הדפיסו Found: Book[title=Emma, author=Austen] ואז No book titled 'Hamlet' on the shelf (asked for: Hamlet).
BookNotFoundException (checked) keeps the requested title and builds a message. Shelf.find returns a book or throws. Print Found: Book[title=Emma, author=Austen] then No book titled 'Hamlet' on the shelf (asked for: Hamlet).
סימולציה: הפתרון רץ שורה אחרי שורה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.List;
public class Main {
public static void main(String[] args) {
Shelf shelf = new Shelf(List.of(new Book("Dune", "Herbert"), new Book("Emma", "Austen")));
for (String t : List.of("Emma", "Hamlet")) {
try {
System.out.println("Found: " + shelf.find(t));
} catch (BookNotFoundException e) {
System.out.println(e.getMessage() + " (asked for: " + e.getTitle() + ")");
}
}
}
}
record Book(String title, String author) {
}
class BookNotFoundException extends Exception {
private final String title;
BookNotFoundException(String title) {
super("No book titled '" + title + "' on the shelf");
this.title = title;
}
String getTitle() {
return title;
}
}
class Shelf {
private final List<Book> books;
Shelf(List<Book> books) {
this.books = List.copyOf(books);
}
Book find(String title) throws BookNotFoundException {
for (Book b : books) {
if (b.title().equals(title)) {
return b;
}
}
throw new BookNotFoundException(title);
}
}Found: Book[title=Emma, author=Austen] No book titled 'Hamlet' on the shelf (asked for: Hamlet)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
חריגות מודחקותSuppressed exceptions
תזכורת: מה ביקשוReminder: the task
הגוף של try-with-resources זורק body failed, וגם close() זורק close failed. איזו חריגה מגיעה ל-catch? הדפיסו body failed ואז suppressed: close failed (עם getSuppressed()).
The body of a try-with-resources throws body failed, and close() throws close failed too. Which exception reaches the catch? Print body failed then suppressed: close failed (with getSuppressed()).
סימולציה: הפתרון רץ שורה אחרי שורה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) {
try (Fragile f = new Fragile()) {
throw new IllegalStateException("body failed");
} catch (Exception e) {
System.out.println(e.getMessage());
for (Throwable s : e.getSuppressed()) {
System.out.println("suppressed: " + s.getMessage());
}
}
}
}
class Fragile implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("close failed");
}
}body failed suppressed: close failed
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
multi-catch ו-finallymulti-catch and finally
תזכורת: מה ביקשוReminder: the task
risky(s) מחזירה 100 / parseInt(s). עבור 4, 0, x תפסו את שתי החריגות האפשריות ב-catch אחד, ו-finally מדפיס checked .... הפלט: 25, checked 4, 0: ArithmeticException, checked 0, x: NumberFormatException, checked x.
risky(s) returns 100 / parseInt(s). For 4, 0, x catch both possible exceptions in one catch, and finally prints checked .... The output: 25, checked 4, 0: ArithmeticException, checked 0, x: NumberFormatException, checked x.
סימולציה: הפתרון רץ שורה אחרי שורה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 risky(String s) {
return 100 / Integer.parseInt(s);
}
public static void main(String[] args) {
for (String s : new String[]{"4", "0", "x"}) {
try {
System.out.println(risky(s));
} catch (ArithmeticException | NumberFormatException e) {
System.out.println(s + ": " + e.getClass().getSimpleName());
} finally {
System.out.println("checked " + s);
}
}
}
}25 checked 4 0: ArithmeticException checked 0 x: NumberFormatException checked x
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.