JavaJava · Chapterبەش 11 · Lectureوانە 11.2

Exceptions: try, catch and finallyهەڵاوێردەکان: try، catch و finally

Handle runtime errors instead of crashing: the exception object, try and catch, the common exceptions with their real messages, several catch blocks and multi-catch, finally, the family of checked and unchecked exceptions, catch or declare with throws, throw and your own exception classes, a safe input loop with Locale.ROOT, try-with-resources, and why an empty catch is dangerous.

لە جیاتی وەستان چارەسەر بکە: ، try و catch، باو بە پەیامە ڕاستەقینەکانیانەوە، چەند بەشێکی catch و catchـی چەندجۆری، finally، خێزانی پشکنراو و نەپشکنراو، گرتن یان ڕاگەیاندن بە throws، throw و خۆت، سەلامەتی بە ⁦Locale.ROOT⁩، و بۆچی catchـی بەتاڵ مەترسیدارە.

20 min read17 خولەک خوێندنەوە · 19 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Catch exceptions with try and catch, read the exception object, and explain which lines are skipped.
  • Use several catch blocks in the right order, multi-catch and finally.
  • Tell checked from unchecked exceptions and fix 'must be caught or declared to be thrown'.
  • Throw exceptions with throw, declare them with throws and write your own exception class.
  • Write a safe input loop and close resources with try-with-resources.
  • بە try و catch بگریت، بخوێنیتەوە و ڕوونی بکەیتەوە کام دێڕ تێدەپەڕێنرێت.
  • چەند بەشێکی catch بە ڕیزی دروست، catchـی چەندجۆری و finally بەکار بهێنیت.
  • لە نەپشکنراوەکان جیا بکەیتەوە و ⁦'must be caught or declared to be thrown'⁩ چاک بکەیت.
  • بە throw فڕێ بدەیت، بە throws ڕایانبگەیەنیت و خۆت بنووسیت.
  • سەلامەتی بنووسیت و بە دابخەیت.

When a program crashesکاتێک بەرنامەیەک دەوەستێت

A runtime error stops a program in the middle (Runtime errors). Java reports it by throwing an : an object that says what went wrong. Turning text into a number is a classic case: Integer.parseInt("42") gives 42, but Integer.parseInt("abc") has no number to give:

لە ناوەڕاستدا دەوەستێنێت (هەڵەکانی کاتی جێبەجێکردن). Java ئەمە بە فڕێدانی ڕادەگەیەنێت: کە دەڵێت چی هەڵە چوو. گۆڕینی دەق بۆ ژمارە نموونەیەکی ناسراوە: Integer.parseInt("42") ⁦42⁩ دەدات، بەڵام Integer.parseInt("abc") هیچ ژمارەیەکی نییە بیدات:

ParseCrash.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ParseCrash {
    public static void main(String[] args) {
        String text = "abc";
        System.out.println("Converting " + text);
        int number = Integer.parseInt(text);
        System.out.println("Twice: " + number * 2);
    }
}
The terminal output of java ParseCrash: Converting abc, then Exception in thread "main" java.lang.NumberFormatException: For input string: "abc", then four "at" lines ending with at ParseCrash.main(ParseCrash.java:5). Three cards below take it apart: the type, its class, NumberFormatException; the message, getMessage(), For input string: "abc"; where, the stack trace, ParseCrash.java:5. Note: read it from the top; the first "at" line that names your file is your line.دەرخستەی java ParseCrash لە تێرمیناڵدا: Converting abc، پاشان Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"، پاشان چوار دێڕی "at" کە بە at ParseCrash.main(ParseCrash.java:5) کۆتایی دێن. سێ کارت لە خوارەوە لێکی دەکەنەوە: جۆرەکە، کلاسەکەی، NumberFormatException؛ پەیامەکە، getMessage()، For input string: "abc"؛ لە کوێ، ڕێچکەی هەڵەکە، ParseCrash.java:5. تێبینی: لە سەرەوە بیخوێنەوە؛ یەکەم دێڕی "at" کە ناوی فایلەکەت تێدایە دێڕەکەی خۆتە.
Type, message and stack traceجۆر، پەیام و CêIT

Twice: was never printed: the program stopped at line 5. Until now you read such a stack trace to fix the code (Reading a stack trace). Some problems, though, come from outside: a user types abc, a file is missing. The program cannot prevent them, but it can handle them, and that is what this lesson teaches.

Twice: هەرگیز چاپ نەکرا: لە دێڕی 5 وەستا. تا ئێستا لەم جۆرەت دەخوێندەوە بۆ ئەوەی کۆدەکە چاک بکەیت (خوێندنەوەی ڕێچکەی هەڵە). بەڵام هەندێک کێشە لە دەرەوە دێن: abc دەنووسێت، نییە. ناتوانێت ڕێگرییان لێ بکات، بەڵام دەتوانێت چارەسەریان بکات و ئەم وانەیە ئەوە فێر دەکات.

Catching an exception: try and catchگرتنی هەڵاوێردەیەک: try و catch

Put the risky lines in a try block, and in a catch block say what to do when one exception type happens. If nothing is thrown, the catch block is skipped. If that exception is thrown, Java jumps to the catch block, and after it the program goes on normally. This is :

دێڕە مەترسیدارەکان بخەرە ناو بەشی tryـەوە و لە بەشی catchـدا بڵێ چی بکرێت کاتێک جۆرێکی ڕوو دەدات. ئەگەر هیچ فڕێ نەدرێت، بەشی catch تێدەپەڕێنرێت. ئەگەر ئەو فڕێ بدرێت، Java باز دەدات بۆ بەشی catch و دوای ئەو بە ئاسایی بەردەوام دەبێت. ئەمە :

CatchIt.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CatchIt {
    public static void main(String[] args) {
        String text = "abc";
        try {
            int number = Integer.parseInt(text);
            System.out.println("Twice: " + number * 2);
        } catch (NumberFormatException e) {
            System.out.println("Not a whole number: " + text);
        }
        System.out.println("The program goes on");
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-6

The risky lines: line 6 is skipped if line 5 throws.

دێڕە مەترسیدارەکان: ئەگەر دێڕی 5 فڕێ بدات، دێڕی 6 تێدەپەڕێنرێت.

Lineدێڕی 7-9

Runs only when a NumberFormatException is thrown in the try block.

تەنیا کاتێک جێبەجێ دەبێت کە NumberFormatException لە بەشی tryـدا فڕێ بدرێت.

The same program with text = "21"هەمان بەرنامە بە ⁦text = "21"⁩
$ java CatchIt
Twice: 42
The program goes on
The program CatchIt with its parts coloured. Lines 1 to 3, try: the risky lines; if a line throws, the rest of try is skipped. Line 4, catch (NumberFormatException e): which exception, and e is the exception object. Lines 5 and 6: run only when it is caught. Line 7, after the try statement: runs either way, the program goes on.بەرنامەی CatchIt بە بەشە ڕەنگکراوەکانییەوە. دێڕی 1 تا 3، try: دێڕە مەترسیدارەکان؛ ئەگەر دێڕێک فڕێ بدات، باقیی try تێدەپەڕێنرێت. دێڕی 4، catch (NumberFormatException e): کام هەڵاوێردە؛ e ئۆبجێکتی هەڵاوێردەکەیە. دێڕی 5 و 6: تەنیا کاتێک دەگیرێت جێبەجێ دەبن. دێڕی 7، دوای try: لە هەردوو حاڵەتدا جێبەجێ دەبێت و بەرنامەکە بەردەوام دەبێت.
try holds the risk, catch holds the answertry مەترسییەکە هەڵدەگرێت، catch وەڵامەکەCêIT
Exception Handling in Java TutorialCoding with John · Englishئینگلیزی · 609K viewsبینین · 20K likesلایک · Partبەشی 0:00–6:03 (ofلە 13:20)

Exceptions in Java: what happens when a program crashes, catching an exception with try and catch, several catch blocks, one catch for two types, and the finally block.

لە Javaـدا: کاتێک لە ناکاو دەوەستێت چی ڕوودەدات، گرتنی بە try و catch، چەند بلۆکی catch، یەک catch بۆ دوو جۆر و بلۆکی finally.

Watch 0:00–6:03: what an exception is, then try and catch blocks.

لە ⁦0:00⁩ تا ⁦6:03⁩ سەیر بکە: چییە، پاشان بلۆکەکانی try و catch.

Catching an exception: try and catchگرتنی هەڵاوێردەیەک: try و catch

Inside the catch: the exception object eلە ناو catchـدا: ئۆبجێکتی هەڵاوێردە، e

In catch (NumberFormatException e), e is the exception object, like a parameter. e.getMessage() gives only the message, printing e gives the type and the message, and e.printStackTrace() prints the whole stack trace, while the program goes on:

لە catch (NumberFormatException e)ـدا، e ، وەک . e.getMessage() تەنیا پەیامەکە دەدات، چاپکردنی e جۆر و پەیامەکە دەدات و e.printStackTrace() هەموو چاپ دەکات، لە کاتێکدا بەردەوام دەبێت:

ExceptionParts.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ExceptionParts {
    public static void main(String[] args) {
        try {
            int number = Integer.parseInt("abc");
            System.out.println(number);
        } catch (NumberFormatException e) {
            System.out.println("getMessage(): " + e.getMessage());
            System.out.println("the object:   " + e);
            e.printStackTrace();
        }
        System.out.println("The program goes on");
    }
}

A message helps the user; the stack trace helps you, the programmer. A real program shows the user a short sentence and keeps the stack trace for the developers, for example in a log file.

پەیامێک یارمەتیی دەدات؛ یارمەتیی تۆی دەدات. ڕاستەقینە ڕستەیەکی کورت پیشانی دەدات و بۆ هەڵدەگرێت، بۆ نموونە لە .

Catch the exceptions you expectئەو جۆرە هەڵاوێردەیەی چاوەڕێی دەکەیت بیگرە

A catch block catches only its own type, and the types below it in the family (soon). Everything else passes by, and the program stops as before. Here the text is a good number, 0, but the division by zero throws something else:

بەشی catch تەنیا جۆری خۆی دەگرێت، لەگەڵ ئەو جۆرانەی لە خێزانەکەدا لە خوارییەوەن (بەم زووانە). هەموو شتێکی تر تێدەپەڕێت و وەک پێشتر دەوەستێت. لێرە دەقەکە ژمارەیەکی دروستە، 0، بەڵام دابەشکردن بەسەر سفردا شتێکی تر فڕێ دەدات:

WrongCatch.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class WrongCatch {
    public static void main(String[] args) {
        String text = "0";
        try {
            int friends = Integer.parseInt(text);
            System.out.println("Each friend pays " + 30000 / friends + " dinars");
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        }
        System.out.println("Done");
    }
}
A catch block, catch (NumberFormatException e), handled here. A NumberFormatException, from "abc" in parseInt, matches and goes in, with a tick. An ArithmeticException passes by on a dashed line, with a cross, and reaches a stop sign: not caught, the program stops with a stack trace.بەشێکی catch، catch (NumberFormatException e)، لێرە چارەسەر دەکرێت. NumberFormatExceptionـێک، لە "abc"ـی ناو parseIntـەوە، دەگونجێت و دەچێتە ژوورەوە، بە نیشانەی ڕاست. ArithmeticExceptionـێک بە هێڵێکی پچڕپچڕ تێدەپەڕێت (خەتی لێ دراوە) و دەگاتە نیشانەی وەستان: نەگیرا، بەرنامەکە بە ڕێچکەیەکی هەڵەوە دەوەستێت.
A catch has the shape of its typecatch شێوەی جۆرەکەی خۆی هەیەCêIT

These are the exceptions you will meet most often. The messages are real, from JDK 17:

ئەمانە باوترین کە دەیانبینیت. پەیامەکان ڕاستەقینەن، لە ⁦JDK 17⁩ـەوە:

Common exceptions and their real messages باو و پەیامە ڕاستەقینەکانیان
ExceptionTypical causeهۆکاری باوMessageپەیام
ArithmeticExceptiona whole number divided by 0 دابەش بەسەر 0دا/ by zero
NumberFormatExceptionInteger.parseInt("abc")Integer.parseInt("abc")For input string: "abc"
InputMismatchExceptionnextInt() reads abc (Wrong input)nextInt() abc دەخوێنێتەوە (نێوخستەی هەڵە)no messageبێ پەیام
ArrayIndexOutOfBoundsExceptionmarks[3] on length 3 (Outside the array)marks[3] بە درێژیی 3 (دەرەوەی ڕیزەک)Index 3 out of bounds for length 3
StringIndexOutOfBoundsException"Java".charAt(9) (Outside the string)"Java".charAt(9) (دەرەوەی زنجیرەنووسە)String index out of range: 9
NullPointerExceptiona method called on null (null); a switch on a null String stops the same way (A null String) لەسەر null بانگ کراوە (null)؛ switchـێک لەسەر Stringـێکی nullیش بە هەمان شێوە دەوەستێت (Stringـی null)Cannot invoke "String.length()" because "<local1>" is null
ConcurrentModificationExceptionremoving inside a for-each loop (HashMap and HashSet)لابردن لە ناو (HashMap و HashSet)no messageبێ پەیام
IllegalArgumentExceptiona method refuses a value (throw) ڕەت دەکاتەوە (throw)your own messageپەیامی خۆت

Catch the exceptions you expectئەو جۆرە هەڵاوێردەیەی چاوەڕێی دەکەیت بیگرە

Several catch blocksچەند بەشێکی catch

One try can have several catch blocks. Java checks them from the top and runs the first one whose type matches; the others are skipped. Each pass of this loop meets a different exception:

یەک try دەتوانێت چەند بەشێکی catchـی هەبێت. Java لە سەرەوە دەیانپشکنێت و یەکەمیان کە جۆرەکەی بگونجێت جێبەجێ دەکات؛ ئەوانی تر تێدەپەڕێنرێن. لە هەر ئەم جیاواز ڕوو دەدات:

SeveralCatches.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SeveralCatches {
    public static void main(String[] args) {
        String[] answers = {"4", "0", "four"};
        for (int i = 0; i <= 3; i++) {
            try {
                int friends = Integer.parseInt(answers[i]);
                System.out.println("Each of " + friends + " friends pays " + 30000 / friends + " dinars");
            } catch (NumberFormatException e) {
                System.out.println("\"" + answers[i] + "\" is not a whole number");
            } catch (ArithmeticException e) {
                System.out.println("Nobody to share the bill with");
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("There is no answer number " + i);
            }
        }
    }
}
Two panels. Wrong order: catch (Exception e) above catch (ArithmeticException e), which is greyed out with a cross: Exception already catches every exception, so the second block can never run, and javac says error: exception ArithmeticException has already been caught. Right order, with a tick: catch (ArithmeticException e), catch (NumberFormatException e), then the wide catch (Exception e); Java tries them from the top, the first that matches runs, and Exception last catches the rest.دوو بەش. ڕیزی هەڵە: catch (Exception e) لە سەرووی catch (ArithmeticException e)ـەوە کە خۆڵەمێشییە و خەتی لێدراوە: Exception پێشتر هەموو هەڵاوێردەیەک دەگرێت، بۆیە بەشی دووەم هەرگیز جێبەجێ نابێت و javac دەڵێت error: exception ArithmeticException has already been caught. ڕیزی دروست، بە نیشانەی ڕاست: catch (ArithmeticException e)، catch (NumberFormatException e)، پاشان catch (Exception e)ـی فراوان؛ Java لە سەرەوە تاقییان دەکاتەوە، یەکەم دانە کە بگونجێت جێبەجێ دەبێت و Exception لە کۆتاییدا باقییەکە دەگرێت.
Specific first, general lastتایبەت سەرەتا، گشتی لە کۆتاییداCêIT

Order matters. A general catch (Exception e) above a specific one would catch everything first, so javac refuses the block that can never run:

ڕیزبەندی گرنگە. catch (Exception e)ـی گشتی لە سەرووی دانەیەکی تایبەتەوە سەرەتا هەموو شتێک دەگرێت، بۆیە javac ئەو بەشە ڕەت دەکاتەوە کە هەرگیز جێبەجێ نابێت:

Outputدەرئەنجام
$ javac CatchOrder.java
CatchOrder.java:7: error: exception ArithmeticException has already been caught
        } catch (ArithmeticException e) {
          ^
1 error

Catch the exceptions you expectئەو جۆرە هەڵاوێردەیەی چاوەڕێی دەکەیت بیگرە

One catch for two types: |یەک catch بۆ دوو جۆر: |

When two exceptions need the same handling, name both in one catch block, separated by | (Java 7 and later). e.getMessage() then shows which problem it was:

کاتێک دوو پێویستیان بە هەمان چارەسەر هەیە، هەردووکیان لە یەک بەشی catchـدا بنووسە و بە | جیایان بکەرەوە (⁦Java 7⁩ و دواتر). پاشان e.getMessage() پیشان دەدات کامە کێشە بوو:

MultiCatch.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class MultiCatch {
    public static void main(String[] args) {
        String[] answers = {"4", "0", "four"};
        for (String answer : answers) {
            try {
                int friends = Integer.parseInt(answer);
                System.out.println("Each pays " + 30000 / friends + " dinars");
            } catch (NumberFormatException | ArithmeticException e) {
                System.out.println("Cannot share the bill with \"" + answer + "\": " + e.getMessage());
            }
        }
    }
}
Two exceptions, NumberFormatException and ArithmeticException, both lead into one block: catch (NumberFormatException | ArithmeticException e), the same handling for both, one block, no copy. Below, with a cross: catch (NumberFormatException | IllegalArgumentException e) is refused, because NumberFormatException is already a kind of IllegalArgumentException; so catch only the parent, catch (IllegalArgumentException e).دوو هەڵاوێردە، NumberFormatException و ArithmeticException، هەردووکیان دەچنە یەک بەشەوە: catch (NumberFormatException | ArithmeticException e)، هەمان چارەسەر بۆ هەردووکیان، یەک بەش، بێ کۆپی. لە خوارەوە، بە خەتلێدان: catch (NumberFormatException | IllegalArgumentException e) ڕەت دەکرێتەوە، چونکە NumberFormatException خۆی جۆرێکە لە IllegalArgumentException؛ بۆیە تەنیا باوکەکە بگرە، catch (IllegalArgumentException e).
One block, two types; never a parent and its childیەک بەش، دوو جۆر؛ هەرگیز باوک و منداڵی خۆی ناCêIT

The types joined by | may not be parent and child. javac refuses NumberFormatException | IllegalArgumentException:

ئەو جۆرانەی بە | پێکەوە دەبەسترێن نابێت باوک و منداڵ بن. javac NumberFormatException | IllegalArgumentException ڕەت دەکاتەوە:

Outputدەرئەنجام
$ javac Related.java
Related.java:5: error: Alternatives in a multi-catch statement cannot be related by subclassing
        } catch (NumberFormatException | IllegalArgumentException e) {
                                         ^
  Alternative NumberFormatException is a subclass of alternative IllegalArgumentException
1 error

finally: it always runsfinally: هەمیشە جێبەجێ دەبێت

A finally block after the catch blocks runs every time the try statement ends: after a normal run, after a caught exception, and even when no catch block matches: then finally runs first, and the exception goes on to the caller (here nobody catches it, so the program stops). Put there the work that must happen in any case:

بەشی finally لە دوای بەشەکانی catch هەر جارێک try کۆتایی دێت جێبەجێ دەبێت: دوای جێبەجێبوونێکی ئاسایی، دوای گیراو و تەنانەت کاتێک هیچ بەشێکی catch نەگونجێت: ئەوکاتە سەرەتا finally جێبەجێ دەبێت، پاشان دەچێت بۆ (لێرە کەس نایگرێت، بۆیە دەوەستێت). ئەو کارەی لە هەموو حاڵەتێکدا دەبێت بکرێت لەوێ دابنێ:

FinallyRuns.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class FinallyRuns {
    static void share(String answer) {
        System.out.println("Answer: " + answer);
        try {
            int friends = Integer.parseInt(answer);
            System.out.println("Each pays " + 30000 / friends + " dinars");
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        } finally {
            System.out.println("finally runs");
        }
    }

    public static void main(String[] args) {
        share("4");
        share("four");
        share("0");
        System.out.println("This line is never reached");
    }
}
Three paths. share("4"), no exception: try runs all its lines, then finally, then the next line; output Each pays 7500 dinars, finally runs. share("four"), caught NumberFormatException: try throws, catch, finally, next line; output Not a number, finally runs. share("0"), not caught ArithmeticException: try throws, no matching catch, an arrow goes round to finally, then a stop sign: the program stops; output finally runs, then Exception in thread "main".سێ ڕێگە. share("4")، بێ هەڵاوێردە: try هەموو دێڕەکانی جێبەجێ دەکات، پاشان finally، پاشان دێڕی دواتر؛ دەرخستە: Each pays 7500 dinars، finally runs. share("four")، NumberFormatExceptionی گیراو: try فڕێ دەدات، catch، finally، دێڕی دواتر؛ دەرخستە: Not a number، finally runs. share("0")، ArithmeticExceptionی نەگیراو: try فڕێ دەدات، هیچ catchـێکی گونجاو نییە، تیرێک بە دەوریدا دەچێتە finally، پاشان نیشانەی وەستان: بەرنامەکە دەوەستێت؛ دەرخستە: finally runs، پاشان Exception in thread "main".
Three ways out of try; finally on all of themسێ ڕێگەی دەرچوون لە try؛ finally لە هەموویانداCêIT
Exception Handling in Java TutorialCoding with John · Englishئینگلیزی · 609K viewsبینین · 20K likesلایک · Partبەشی 8:27–13:20 (ofلە 13:20)

Exceptions in Java: what happens when a program crashes, catching an exception with try and catch, several catch blocks, one catch for two types, and the finally block.

لە Javaـدا: کاتێک لە ناکاو دەوەستێت چی ڕوودەدات، گرتنی بە try و catch، چەند بلۆکی catch، یەک catch بۆ دوو جۆر و بلۆکی finally.

Watch 8:27 to the end: the finally block and when it runs.

لە ⁦8:27⁩ تا کۆتایی سەیر بکە: بلۆکی finally و کەی جێبەجێ دەبێت.

finally: it always runsfinally: هەمیشە جێبەجێ دەبێت

Step by step: where the program jumpsهەنگاو بە هەنگاو: بەرنامەکە بۆ کوێ باز دەدات

The animation runs one try statement with the answer "0", then with "4". Watch which lines run, which are skipped, and where the program jumps:

ئەنیمەیشنەکە یەک try بە وەڵامی "0" جێبەجێ دەکات، پاشان بە "4". سەیر بکە کام دێڕ جێبەجێ دەبێت، کام تێدەپەڕێنرێت و بۆ کوێ باز دەدات:

An animation of a twelve-line try statement with answer "0". Line 2 runs: friends = 0. Line 3, 30000 / friends, throws an ArithmeticException (/ by zero). Line 4 is crossed out as skipped, and an arrow jumps to catch (NumberFormatException e), which does not match. catch (ArithmeticException e) matches and line 8 prints Nobody to share with; then finally prints finally runs, and line 12, after the try statement, prints Next answer. The last frame uses answer "4": lines 2 to 4 run and print Each pays 7500, both catch blocks are skipped, and finally runs and Next answer is printed.
An animation of a twelve-line try statement with answer "0". Line 2 runs: friends = 0. Line 3, 30000 / friends, throws an ArithmeticException (/ by zero). Line 4 is crossed out as skipped, and an arrow jumps to catch (NumberFormatException e), which does not match. catch (ArithmeticException e) matches and line 8 prints Nobody to share with; then finally prints finally runs, and line 12, after the try statement, prints Next answer. The last frame uses answer "4": lines 2 to 4 run and print Each pays 7500, both catch blocks are skipped, and finally runs and Next answer is printed.
Thrown at line 3, caught at line 7, finally at line 9لە دێڕی 3 فڕێ درا، لە دێڕی 7 گیرا، finally لە دێڕی 9CêIT

The same try statement inside a method, called with both answers; the real output matches the animation:

هەمان try لە ناو ، بە هەردوو وەڵامەکە بانگ کراوە؛ ڕاستەقینە لەگەڵ ئەنیمەیشنەکە دەگونجێت:

ShareBill.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class ShareBill {
    static void share(String answer) {
        try {
            int friends = Integer.parseInt(answer);
            int each = 30000 / friends;
            System.out.println("Each pays " + each);
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        } catch (ArithmeticException e) {
            System.out.println("Nobody to share with");
        } finally {
            System.out.println("finally runs");
        }
        System.out.println("Next answer");
    }

    public static void main(String[] args) {
        share("0");
        share("4");
    }
}

The exception family: checked and uncheckedخێزانی هەڵاوێردەکان: پشکنراو و نەپشکنراو

Exceptions are classes, and they form a family through inheritance (extends). At the top is Throwable with two branches: Error for serious problems that a program should not try to catch, such as StackOverflowError (Stack overflow), and Exception for problems a program can handle. A catch for a parent type also catches its children: catch (RuntimeException e) catches an ArithmeticException too.

و لە ڕێگەی خێزانێک پێک دەهێنن (extends). لە سەرەوە Throwable هەیە بە دوو لق: Error بۆ کێشەی گەورە کە نابێت هەوڵی گرتنیان بدات، وەک StackOverflowError (سەرڕێژبوونی ستاک)؛ Exceptionیش بۆ ئەو کێشانەی دەتوانێت چارەسەریان بکات. catchـێک بۆ جۆرێکی باوک منداڵەکانیشی دەگرێت: catch (RuntimeException e) ArithmeticExceptionیش دەگرێت.

A family tree. Throwable at the top. Error, unchecked, with StackOverflowError and OutOfMemoryError. Exception with IOException, checked, holding FileNotFoundException and NoSuchFileException; InterruptedException, checked; and RuntimeException, unchecked, holding ArithmeticException, NumberFormatException (via IllegalArgumentException), InputMismatchException (via NoSuchElementException), ArrayIndexOutOfBoundsException (via IndexOutOfBoundsException), NullPointerException and ConcurrentModificationException. Legend: checked, javac makes you catch them or declare them with throws, for files, the network, waiting; unchecked, RuntimeException, Error and their subclasses, javac does not check them, they usually mean a bug. Each line means is a kind of: the family is inheritance. Checked with getSuperclass() on JDK 17.دارێکی خێزان. Throwable لە سەرەوە. Error، نەپشکنراو، بە StackOverflowError و OutOfMemoryError. Exception بە IOException، پشکنراو، کە FileNotFoundException و NoSuchFileExceptionـی تێدایە؛ InterruptedException، پشکنراو؛ و RuntimeException، نەپشکنراو، کە ArithmeticException، NumberFormatException (لە ڕێگەی IllegalArgumentExceptionـەوە)، InputMismatchException (لە ڕێگەی NoSuchElementExceptionـەوە)، ArrayIndexOutOfBoundsException (لە ڕێگەی IndexOutOfBoundsExceptionـەوە)، NullPointerException و ConcurrentModificationExceptionـی تێدایە. ڕوونکردنەوە: پشکنراو، javac ناچارت دەکات بیانگریت یان بە throws ڕایانبگەیەنیت، بۆ فایلەکان، ڕایەڵە، چاوەڕوانی؛ نەپشکنراو، RuntimeException، Error و کلاسەکانی منداڵیان، javac نایانپشکنێت، زۆرجار واتای باگێک دەدەن. هەر هێڵێک واتە جۆرێکە لە: ئەم خێزانە بۆماوەیە. لە JDK 17 بە getSuperclass() پشکنرا.
Blue: checked. Orange: unchecked.شین: پشکنراو. پرتەقاڵی: نەپشکنراو.CêIT

are RuntimeException, Error and their subclasses: javac does not make you handle them, because they usually show a that you should fix in the code. All the others are : javac checks that your code deals with them. The next screen shows how.

بریتین لە RuntimeException، Error و : javac ناچارت ناکات مامەڵەیان لەگەڵ بکەیت، چونکە زۆرجار پیشان دەدەن کە دەبێت لە کۆدەکەدا چاکی بکەیت. هەموو ئەوانی تر : javac دەپشکنێت کە کۆدەکەت مامەڵەیان لەگەڵ دەکات. پەڕەی داهاتوو پیشانی دەدات چۆن.

Checked exceptions: catch or declareهەڵاوێردە پشکنراوەکان: بیگرە یان ڕایبگەیەنە

A Scanner can read a file as well as the keyboard: new Scanner(new File("notes.txt")). If the file is missing, it throws a FileNotFoundException, a checked exception, so javac refuses code that ignores it:

Scanner دەتوانێت بخوێنێتەوە وەک چۆن دەخوێنێتەوە: new Scanner(new File("notes.txt")). ئەگەر نەبێت، FileNotFoundException فڕێ دەدات، کە ، بۆیە javac ئەو کۆدە ڕەت دەکاتەوە کە گوێی پێ نادات:

ReadNotes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.io.File;
import java.util.Scanner;

public class ReadNotes {
    public static void main(String[] args) {
        Scanner reader = new Scanner(new File("notes.txt"));
        System.out.println(reader.nextLine());
    }
}
Definitionپێناسە

An that the checks for: a method that can throw it, such as IOException from work with files, must either catch it or name it after throws, or the program does not compile. Compare .

کە دەیپشکنێت: کە دەتوانێت فڕێی بدات، وەک IOException لە کارکردن لەگەڵ ، یان دەبێت بیگرێت یان دوای throws ناوی بهێنێت، ئەگەر نا کۆمپایل نابێت. بەراوردی بکە لەگەڵ .

A decision diagram. The line Scanner reader = new Scanner(new File("notes.txt")); can throw FileNotFoundException, a checked exception. javac asks: caught or declared? Neither, with a cross: error: unreported exception FileNotFoundException; must be caught or declared to be thrown. Catch it here: try { ... } catch (FileNotFoundException e) { ... }. Declare it: main(String[] args) throws FileNotFoundException, and the caller must handle it. Note: unchecked exceptions (RuntimeException ...) need neither.هێڵکارییەکی بڕیار. دێڕی Scanner reader = new Scanner(new File("notes.txt")); دەتوانێت FileNotFoundException فڕێ بدات، هەڵاوێردەیەکی پشکنراو. javac دەپرسێت: گیراوە یان ڕاگەیەنراوە؟ هیچیان، بە خەتلێدان: error: unreported exception FileNotFoundException; must be caught or declared to be thrown. لێرە بیگرە: try { ... } catch (FileNotFoundException e) { ... }. ڕایبگەیەنە: main(String[] args) throws FileNotFoundException و بانگکەر دەبێت چارەسەری بکات. تێبینی: هەڵاوێردە نەپشکنراوەکان (RuntimeException ...) پێویستیان بە هیچیان نییە.
javac checks: caught or declared?javac دەپشکنێت: گیراوە یان ڕاگەیەنراوە؟CêIT

Fix 1, catch it: the program decides what to do. We ran it once without notes.txt and once after creating it:

چارەسەری 1، بیگرە: خۆی بڕیار دەدات چی بکات. جارێک بەبێ notes.txt و جارێک دوای دروستکردنی جێبەجێمان کرد:

ReadNotes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadNotes {
    public static void main(String[] args) {
        try {
            Scanner reader = new Scanner(new File("notes.txt"));
            System.out.println("First line: " + reader.nextLine());
            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("Could not open the file: " + e.getMessage());
        }
    }
}

Fix 2, declare it with throws after the brackets of the method. The method hands the problem to its caller; for main that is the JVM, which prints the stack trace:

چارەسەری 2، ڕایبگەیەنە بە throws لە دوای کەوانەکانی . کێشەکە دەداتە دەست ؛ بۆ main ئەوە JVMـە، کە چاپ دەکات:

ReadNotes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadNotes {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(new File("notes.txt"));
        System.out.println("First line: " + reader.nextLine());
        reader.close();
    }
}

Throwing an exception yourself: throwفڕێدانی هەڵاوێردەیەک بە دەستی خۆت: throw

You met throw once already: in Removing an element it refuses an index outside the array. Your own methods can refuse a bad value with throw and a new exception object. throw ends the method at once, like return, and the exception travels to the caller:

پێشتر جارێک throwـت بینی: لە لابردنی دانەیەکـدا دەرەوەی ڕەت دەکاتەوە. خۆت دەتوانن خراپ بە throw و نوێ ڕەت بکەنەوە. throw یەکسەر کۆتایی پێ دەهێنێت (وەک return) و دەچێت بۆ :

CheckMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CheckMark {
    static void saveMark(int mark) {
        if (mark < 0 || mark > 100) {
            throw new IllegalArgumentException("a mark must be 0 to 100, not " + mark);
        }
        System.out.println(mark + " saved");
    }

    public static void main(String[] args) {
        saveMark(85);
        saveMark(120);
        System.out.println("This line is never reached");
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

IllegalArgumentException is Java's usual unchecked exception for a bad argument.

IllegalArgumentException نەپشکنراوی ئاسایی Javaـیە بۆ خراپ.

Two stacked method frames. On top saveMark(120): if (mark < 0 || mark > 100) { throw new IllegalArgumentException("a mark must be 0 to 100, not " + mark); }. Below it main: try { saveMark(mark); } catch (IllegalArgumentException e) { print "Refused: " ... }. An arrow shows the exception leaving saveMark and landing in the caller's catch. Right: with the catch in main the output is 85 saved, Refused: a mark must be 0 to 100, not 120; without any catch the output is IllegalArgumentException with the lines at CheckMark.saveMark(...:4) and at CheckMark.main(...:11).دوو چوارچێوەی میتۆد لەسەر یەک. لە سەرەوە saveMark(120): if (mark < 0 || mark > 100) { throw new IllegalArgumentException("a mark must be 0 to 100, not " + mark); }. لە خوارییەوە main: try { saveMark(mark); } catch (IllegalArgumentException e) { چاپی "Refused: " ... }. تیرێک پیشان دەدات هەڵاوێردەکە لە saveMark دەردەچێت و دەچێتە ناو catchـی بانگکەر. لای ڕاست: بە catchـەکەی ناو main دەرخستەکە دەبێتە 85 saved، Refused: a mark must be 0 to 100, not 120؛ بەبێ هیچ catchـێک دەرخستەکە IllegalArgumentExceptionـە لەگەڵ دێڕەکانی at CheckMark.saveMark(...:4) و at CheckMark.main(...:11).
throw ends the method; the caller catchesthrow کۆتایی پێ دەهێنێت؛ دەیگرێتCêIT

The caller can catch it and carry on with the next value:

دەتوانێت بیگرێت و بە دواتر بەردەوام بێت:

CheckMarks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CheckMarks {
    static void saveMark(int mark) {
        if (mark < 0 || mark > 100) {
            throw new IllegalArgumentException("a mark must be 0 to 100, not " + mark);
        }
        System.out.println(mark + " saved");
    }

    public static void main(String[] args) {
        int[] typed = {85, 120, 47};
        for (int mark : typed) {
            try {
                saveMark(mark);
            } catch (IllegalArgumentException e) {
                System.out.println("Refused: " + e.getMessage());
            }
        }
    }
}

Your own exception classکلاسی هەڵاوێردەی خۆت

For a problem that belongs to your program, write your own exception class: a class that extends Exception (extends) and hands its message to the parent with super(message) (super(...)). By custom, its name ends in Exception. Because it extends Exception and not RuntimeException, it is checked, so a method that throws it says so with throws:

بۆ کێشەیەک کە هی ، خۆت بنووسە: کە Exception extends دەکات (extends) و بە super(message) پەیامەکەی دەداتە باوکەکەی (⁦super(...)⁩). بە نەریت ناوەکەی بە Exception کۆتایی دێت. چونکە Exception extends دەکات نەک RuntimeException، پشکنراوە، بۆیە کە فڕێی دەدات بە throws دەیڵێت:

MarkBook.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class MarkOutOfRangeException extends Exception {
    MarkOutOfRangeException(String message) {
        super(message);
    }
}

public class MarkBook {
    static void addMark(String name, int mark) throws MarkOutOfRangeException {
        if (mark < 0 || mark > 100) {
            throw new MarkOutOfRangeException(name + ": " + mark + " is not between 0 and 100");
        }
        System.out.println(name + ": " + mark + " saved");
    }

    public static void main(String[] args) throws MarkOutOfRangeException {
        addMark("Aram", 85);
        addMark("Shilan", 105);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-5

A checked exception class: extends Exception, passes the message on.

پشکنراو: Exception extends دەکات و پەیامەکە دەگوازێتەوە.

Lineدێڕی 8

throws is required: the exception is checked.

throws پێویستە: پشکنراوە.

Left: a small family branch, Throwable, Exception and below it MarkOutOfRangeException, with IOException beside it as a checked sister; under it the class: class MarkOutOfRangeException extends Exception { MarkOutOfRangeException(String message) { super(message); } }, with a line below it: super(message) hands the message to Exception. Right: the real output, Aram: 85 saved, then Exception in thread "main" MarkOutOfRangeException: Shilan: 105 is not between 0 and 100, at MarkBook.addMark(MarkBook.java:10), at MarkBook.main(MarkBook.java:17), with colour keys for your class name, your message and where it was thrown.چەپ: لقێکی بچووکی خێزان، Throwable، Exception و لە خوارییەوە MarkOutOfRangeException، لەگەڵ IOException لە تەنیشتییەوە وەک خوشکێکی پشکنراو؛ لە ژێرییەوە کلاسەکە: class MarkOutOfRangeException extends Exception { MarkOutOfRangeException(String message) { super(message); } } و تێبینییەکە: super(message) پەیامەکە دەداتە Exception. ڕاست: دەرخستەی ڕاستەقینە، Aram: 85 saved، پاشان Exception in thread "main" MarkOutOfRangeException: Shilan: 105 is not between 0 and 100، at MarkBook.addMark(MarkBook.java:10)، at MarkBook.main(MarkBook.java:17)، بە ڕەنگی جیا بۆ ناوی کلاسەکەت، پەیامەکەت و ئەو شوێنەی فڕێ درا.
Your class name and your message in a real stack traceناوی و پەیامەکەت لە ڕاستەقینەداCêIT

The caller catches it like any other exception:

وەک هەر تر دەیگرێت:

MarkBookSafe.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class MarkOutOfRangeException extends Exception {
    MarkOutOfRangeException(String message) {
        super(message);
    }
}

public class MarkBookSafe {
    static void addMark(String name, int mark) throws MarkOutOfRangeException {
        if (mark < 0 || mark > 100) {
            throw new MarkOutOfRangeException(name + ": " + mark + " is not between 0 and 100");
        }
        System.out.println(name + ": " + mark + " saved");
    }

    public static void main(String[] args) {
        String[] names = {"Aram", "Shilan", "Karwan"};
        int[] marks = {85, 105, 72};
        for (int i = 0; i < names.length; i++) {
            try {
                addMark(names[i], marks[i]);
            } catch (MarkOutOfRangeException e) {
                System.out.println("Not saved. " + e.getMessage());
            }
        }
    }
}

A safe input loopخولێکی سەلامەتی نێوخستە

Now the program from Wrong input can ask again instead of stopping. Read in a loop; when nextDouble() throws InputMismatchException, take the bad token away with next() and ask again. Locale.ROOT makes the Scanner accept 85.5 on every computer (Locale.ROOT):

ئێستا ئەو نێوخستەی هەڵە دەتوانێت لە جیاتی وەستان دووپاتە بپرسێت. لە بخوێنەوە؛ کاتێک nextDouble() InputMismatchException فڕێ دەدات، پارچە خراپەکە بە next() لاببە و دووپاتە بپرسە. Locale.ROOT وا دەکات Scanner لە هەموو کۆمپیوتەرێکدا 85.5 وەربگرێت (⁦Locale.ROOT⁩):

AskMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class AskMark {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in).useLocale(Locale.ROOT);
        double mark;
        while (true) {
            System.out.print("Mark (0-100): ");
            try {
                mark = input.nextDouble();
                if (mark >= 0 && mark <= 100) {
                    break;                                     // a good mark: leave the loop
                }
                System.out.println(mark + " is outside 0-100.");
            } catch (InputMismatchException e) {
                String bad = input.next();                     // take the bad token out of the input
                System.out.println(bad + " is not a number.");
            }
        }
        System.out.println("Saved: " + mark);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 13-14

A number in range ends the loop with break.

ژمارەیەک لە نێوان 0 و ⁦100⁩دا بە break کۆتایی پێ دەهێنێت.

Lineدێڕی 18

next() takes the bad token away; without it the loop never ends.

⁦next()⁩ پارچە خراپەکە لادەبات؛ بەبێ ئەو هەرگیز کۆتایی نایەت.

A flowchart. Start; print "Mark (0-100): "; mark = nextDouble(); a number? If no (InputMismatchException): bad = input.next(), take the bad token away and say so, then back to the prompt. If yes: 0 to 100? If no: say "outside 0-100" and go back. If yes: break, then Saved: 85.5. A note: Scanner with Locale.ROOT reads 85.5 everywhere.هێڵکارییەکی ڕەوت. دەستپێک؛ print "Mark (0-100): "؛ mark = nextDouble()؛ ژمارەیە؟ ئەگەر نەخێر (InputMismatchException): bad = input.next()، پارچە خراپەکە لاببە و بیڵێ، پاشان بگەڕێوە بۆ پرسیارەکە. ئەگەر بەڵێ: 0 تا 100؟ ئەگەر نەخێر: بڵێ «لە دەرەوەی 0-100» و بگەڕێوە. ئەگەر بەڵێ: break، پاشان Saved: 85.5. تێبینییەک: Scanner بە Locale.ROOT لە هەموو شوێنێک 85.5 دەخوێنێتەوە.
Ask until the answer is usableبپرسە تا وەڵامەکە بەکاربێتCêIT

Checking first with hasNextDouble() works too (Look before you take). If the input ends completely (Ctrl+D; on Windows Ctrl+Z, then Enter), nextDouble() throws NoSuchElementException, the parent of InputMismatchException, which this catch does not catch.

پشکنینی پێشوەختە بە hasNextDouble()یش کار دەکات (پێش وەرگرتن سەیر بکە). ئەگەر بە تەواوی کۆتایی بێت (⁦Ctrl+D⁩؛ لە ⁦Windows Ctrl+Z⁩ و پاشان Enter)، nextDouble() NoSuchElementException فڕێ دەدات، باوکی InputMismatchException، کە ئەم catchـە نایگرێت.

A safe input loopخولێکی سەلامەتی نێوخستە

Forget next(), and the loop never ends⁦next()⁩ لەبیر بکە و خولەکە هەرگیز کۆتایی نایەت

A failed nextDouble() does not take the bad token: it stays at the front of the input. Without input.next() in the catch block, the same ninety fails again and again. We stopped this run with Ctrl+C after one second:

nextDouble()ـی شکستخواردوو پارچە خراپەکە نابات: لە سەرەتای دەمێنێتەوە. بەبێ input.next() لە بەشی catchـدا، هەمان ninety دووپاتە و دووپاتە شکست دەهێنێت. ئەم جێبەجێکردنەمان دوای یەک چرکە بە ⁦Ctrl+C⁩ ڕاگرت:

AskMarkBug.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class AskMarkBug {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in).useLocale(Locale.ROOT);
        double mark;
        while (true) {
            System.out.print("Mark (0-100): ");
            try {
                mark = input.nextDouble();
                if (mark >= 0 && mark <= 100) {
                    break;
                }
                System.out.println(mark + " is outside 0-100.");
            } catch (InputMismatchException e) {
                System.out.println("That is not a number.");   // the bad token is still waiting
            }
        }
        System.out.println("Saved: " + mark);
    }
}
The input as tokens: ninety, 120, 85.5, with ninety marked. nextDouble() looks at "ninety", throws, and leaves it there. A warm box: without input.next() the same token fails again, for ever; in 1 second our run printed 206 577 lines, then Ctrl+C stopped it. After next(): 120, 85.5; input.next() takes "ninety" away and the next try reads 120.نێوخستەکە وەک پارچە: ninety، 120، 85.5، کە ninety نیشانە کراوە. nextDouble() سەیری "ninety" دەکات، فڕێ دەدات و لەوێی دەهێڵێتەوە. سندووقێکی پرتەقاڵی: بەبێ input.next() هەمان پارچە بۆ هەمیشە دووپاتە شکست دەهێنێت؛ لە یەک چرکەدا بەرنامەکەمان 206 577 دێڕی چاپ کرد، پاشان Ctrl+C ڕایگرت. دوای next(): 120، 85.5؛ input.next() "ninety" لادەبات و هەوڵی دواتر 120 دەخوێنێتەوە.
The bad token stays until next() takes itپارچە خراپەکە دەمێنێتەوە تا ⁦next()⁩ دەیباتCêIT

try-with-resources: closing things by itselfڕستەی ⁦try-with-resources⁩: داخستنی شتەکان بە خۆی

Files, Scanners and network connections are resources: a program must close them when it is done with them. With (Java 7 and later) you open them in brackets after try, and Java closes them at the end of the block, even when an exception happens. To watch it, here is a Door class that announces when it opens and closes; it implements the interface AutoCloseable (Interfaces):

، Scannerـەکان و پەیوەندییەکانی : دەبێت دوای تەواوبوونی کارەکەی دایانبخات. بە (⁦Java 7⁩ و دواتر) لە ناو کەوانەدا لە دوای try دەیانکەیتەوە و Java لە کۆتایی بەشەکەدا دایاندەخات، تەنانەت کاتێک ڕوو دەدات. بۆ بینینی ئەمە، سەیری Door بکە کە ڕادەگەیەنێت کەی دەکرێتەوە و کەی دادەخرێت؛ AutoCloseable جێبەجێ دەکات (نێوبەستەکان):

Doors.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Door implements AutoCloseable {
    String name;

    Door(String name) {
        this.name = name;
        System.out.println(name + " opened");
    }

    @Override
    public void close() {
        System.out.println(name + " closed");
    }
}

public class Doors {
    public static void main(String[] args) {
        try (Door front = new Door("Front door");
             Door back = new Door("Back door")) {
            System.out.println("Working inside");
            System.out.println(10 / 0);
            System.out.println("Never printed");
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("finally");
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 17-18

Two resources, opened in the brackets after try.

دوو ، لە ناو کەوانەی دوای tryـدا دەکرێنەوە.

A timeline under the line try (Door front = new Door("Front door"); Door back = new Door("Back door")) {. Eight steps: 1 Front door opened and 2 Back door opened, with open doors; 3 Working inside; 4 10 / 0 throws, with a stop sign; 5 Back door closed and 6 Front door closed, with closed doors; 7 Caught: / by zero; 8 finally. Notes: closed automatically at the end of try, in reverse order (back, then front), before catch and finally, even when an exception happens; works for any AutoCloseable such as Scanner and FileWriter (Java 7 and later); no close() to forget.هێڵی کات لە ژێر دێڕی try (Door front = new Door("Front door"); Door back = new Door("Back door")) {. هەشت هەنگاو: 1 Front door opened و 2 Back door opened، بە دەرگای کراوە؛ 3 Working inside؛ 4 10 / 0 فڕێ دەدات، بە نیشانەی وەستان؛ 5 Back door closed و 6 Front door closed، بە دەرگای داخراو؛ 7 Caught: / by zero؛ 8 finally. تێبینییەکان: لە کۆتایی tryـدا خۆکار دادەخرێن، بە ڕیزی پێچەوانە (back، پاشان front)، پێش catch و finally، تەنانەت کاتێک هەڵاوێردەیەک ڕوو دەدات؛ بۆ هەر AutoCloseableـێک وەک Scanner و FileWriter کار دەکات (Java 7 و دواتر)؛ هیچ close()ـێک نییە لەبیر بچێت.
Opened in the brackets, closed at the braceلە کەوانەکەدا دەکرێتەوە، لە کەوانە گەورەکەدا دادەخرێتCêIT

The doors closed in reverse order, before the catch block ran. The next lesson uses this with real files (Files).

دەرگاکان بە ڕیزی پێچەوانە داخران، پێش ئەوەی بەشی catch جێبەجێ ببێت. وانەی داهاتوو ئەمە لەگەڵ ڕاستەقینە بەکار دەهێنێت (فایلەکان).

Definitionپێناسە

A try that opens its resources in brackets, as in try (Scanner in = new Scanner(file)) { … }, and closes them by itself at the end, even when an happens. It replaces closing files by hand in finally.

tryـێکە کە سەرچاوەکانی لە ناو کەوانەدا دەکاتەوە (try (Scanner in = new Scanner(file)) { … }) و لە کۆتاییدا خۆی دایاندەخات، تەنانەت ئەگەر ڕوو بدات. لە جیاتی داخستنی بە دەست لە finallyـدا بەکار دێت.

Do not catch everything, do not catch silentlyهەموو شتێک مەگرە، بە بێدەنگیش مەیگرە

catch (Exception e) catches every exception, including the ones that show a bug. With an empty block, the bug disappears without a word and the program gives a wrong answer:

catch (Exception e) هەموو دەگرێت، ئەوانەشی کە پیشان دەدەن. بە بەشێکی بەتاڵ، بەبێ هیچ وشەیەک ون دەبێت و وەڵامێکی هەڵە دەدات:

SilentBug.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SilentBug {
    public static void main(String[] args) {
        int[] marks = {80, 90, 70};
        int total = 0;
        int average = 0;
        try {
            for (int i = 0; i <= marks.length; i++) {   // the bug: <= goes one place too far
                total += marks[i];
            }
            average = total / marks.length;
        } catch (Exception e) {
            // nothing here: the error is swallowed
        }
        System.out.println("Average: " + average);
    }
}

The real average is 80. Catch only what you expect, and always say what happened; the same code with a specific catch that prints the exception shows the bug at once:

تێکڕای ڕاستەقینە ⁦80⁩ـە. تەنیا ئەوە بگرە کە چاوەڕێی دەکەیت و هەمیشە بڵێ چی ڕوویدا؛ هەمان کۆد بە catchـێکی تایبەت کە چاپ دەکات یەکسەر پیشان دەدات:

Outputدەرئەنجام
$ java SilentBugShown
Bug: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Average: 0

Common mistakesهەڵە باوەکان

Mistakes with exceptions, with the real messagesهەڵەکان لەگەڵ ، بە پەیامە ڕاستەقینەکانەوە
You wroteنووسیتWhat happensچی ڕوو دەداتFixچارەسەر
A variable declared inside try, used after it لە ناو try ناساندراوە و دوای ئەو بەکار هاتووەerror: cannot find symbol symbol: variable ageDeclare it before try (int age = 0;).پێش try بیناسێنە (int age = 0;).
catch (Exception e) before a specific catchcatch (Exception e) پێش catchـێکی تایبەتerror: exception ArithmeticException has already been caughtSpecific catch blocks first, Exception last.بەشە تایبەتەکانی catch سەرەتا، Exception لە کۆتاییدا.
catch (NumberFormatException | IllegalArgumentException e)error: Alternatives in a multi-catch statement cannot be related by subclassingCatch only the parent type.تەنیا جۆری باوک بگرە.
A checked exception neither caught nor declared کە نە گیراوە نە ڕاگەیەنراوەerror: unreported exception FileNotFoundException; must be caught or declared to be throwntry/catch, or throws on the method.⁦try/catch⁩، یان throws لەسەر .
Throwing your own checked exception without throwsفڕێدانی پشکنراوی خۆت بەبێ throwserror: unreported exception MarkOutOfRangeException; must be caught or declared to be thrownAdd throws MarkOutOfRangeException.throws MarkOutOfRangeException زیاد بکە.
catch (InputMismatchException e) without input.next()catch (InputMismatchException e) بەبێ input.next()an endless loopTake the bad token: input.next().پارچە خراپەکە ببە: input.next().
An empty catch (Exception e) { }catch (Exception e) { }ـی بەتاڵa wrong result and no messageئەنجامێکی هەڵە و هیچ پەیامێکCatch specific types and report them.جۆرە تایبەتەکان بگرە و ڕایانبگەیەنە.
Catching an exception that is really a bugگرتنی کە لە ڕاستیدا the bug stays hidden شاراوە دەمێنێتەوەFix the code, e.g. i < marks.length.کۆدەکە چاک بکە، بۆ نموونە i < marks.length.

The first mistake in full:

یەکەم هەڵە بە تەواوی:

TryScope.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class TryScope {
    public static void main(String[] args) {
        try {
            int age = Integer.parseInt("20");
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        }
        System.out.println(age + 1);
    }
}

Practiceڕاهێنان

ExerciseڕاهێنانA safe divisionدابەشکردنێکی سەلامەت

Read two whole numbers and print their quotient. Print Please type whole numbers only. for bad input and You cannot divide by zero. for a zero divisor.

دوو بخوێنەوە و ئەنجامی دابەشکردنەکەیان چاپ بکە. بۆ خراپ Please type whole numbers only. و بۆ دابەشکەری سفر You cannot divide by zero. چاپ بکە.

Show answerوەڵامەکە پیشان بدە
SafeDivide.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.InputMismatchException;
import java.util.Scanner;

public class SafeDivide {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.print("Dividend: ");
            int a = input.nextInt();
            System.out.print("Divisor: ");
            int b = input.nextInt();
            System.out.println(a + " / " + b + " = " + a / b);
        } catch (InputMismatchException e) {
            System.out.println("Please type whole numbers only.");
        } catch (ArithmeticException e) {
            System.out.println("You cannot divide by zero.");
        }
    }
}

Both reads and the division are in one try; each catch handles one kind of problem.

هەردوو خوێندنەوەکە و دابەشکردنەکە لە یەک tryـدان؛ هەر catchـێک جۆرێک کێشە چارەسەر دەکات.

ExerciseڕاهێنانPredict the outputپێشبینیی دەرخستە بکە

Without running it, write down what this program prints. Then compare with the answer.

بەبێ جێبەجێکردنی، بینووسە ئەم چی چاپ دەکات. پاشان لەگەڵ وەڵامەکە بەراوردی بکە.

Predict.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Predict {
    public static void main(String[] args) {
        int[] numbers = {4, 0, 2};
        for (int n : numbers) {
            try {
                System.out.println("A " + n);
                System.out.println("B " + 8 / n);
            } catch (ArithmeticException e) {
                System.out.println("C");
            } finally {
                System.out.println("D");
            }
        }
        System.out.println("E");
    }
}
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
$ java Predict
A 4
B 2
D
A 0
C
D
A 2
B 4
D
E

For 0, line B throws before it prints, so C runs; D (finally) runs for every number; E comes once after the loop.

بۆ 0، دێڕی B پێش چاپکردن فڕێ دەدات، بۆیە C جێبەجێ دەبێت؛ ⁦D (finally)⁩ بۆ هەموو ژمارەیەک جێبەجێ دەبێت؛ E یەک جار دوای دێت.

ExerciseڕاهێنانNot enough moneyپارە بەس نییە

Write a checked NotEnoughMoneyException and a method withdraw(int amount) that throws it when the amount is more than the balance of 50 000 dinars. Try 20 000, 40 000 and 30 000.

NotEnoughMoneyExceptionـێکی پشکنراو و withdraw(int amount) بنووسە کە فڕێی بدات کاتێک بڕەکە لە باڵانسی ⁦50 000⁩ دینار زیاترە. ⁦20 000⁩، ⁦40 000⁩ و ⁦30 000⁩ تاقی بکەرەوە.

Hintئاماژە

extends Exception, super(message), throws.

extends Exception، ⁦super(message)⁩، throws.

Show answerوەڵامەکە پیشان بدە
Bank.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class NotEnoughMoneyException extends Exception {
    NotEnoughMoneyException(String message) {
        super(message);
    }
}

public class Bank {
    static int balance = 50000;

    static void withdraw(int amount) throws NotEnoughMoneyException {
        if (amount > balance) {
            throw new NotEnoughMoneyException("you asked for " + amount + " but have only " + balance);
        }
        balance -= amount;
        System.out.println("Took " + amount + ", left " + balance);
    }

    public static void main(String[] args) {
        int[] requests = {20000, 40000, 30000};
        for (int amount : requests) {
            try {
                withdraw(amount);
            } catch (NotEnoughMoneyException e) {
                System.out.println("Refused: " + e.getMessage());
            }
        }
    }
}
ExerciseڕاهێنانAdd up the whole numbersژمارە تەواوەکان کۆ بکەرەوە

Add up the whole numbers in "12 7 x 30 4.5 9", skip the rest, and count how many you skipped.

ناو "12 7 x 30 4.5 9" کۆ بکەرەوە، ئەوانی تر تێپەڕێنە و بژمێرە چەندت تێپەڕاند.

Show answerوەڵامەکە پیشان بدە
SumNumbers.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SumNumbers {
    public static void main(String[] args) {
        String line = "12 7 x 30 4.5 9";
        int sum = 0;
        int skipped = 0;
        for (String part : line.split(" ")) {
            try {
                sum += Integer.parseInt(part);
            } catch (NumberFormatException e) {
                skipped++;
            }
        }
        System.out.println("Sum: " + sum + ", skipped: " + skipped);
    }
}

x and 4.5 throw NumberFormatException in parseInt; the catch counts them: 12 + 7 + 30 + 9 = 58.

x و 4.5 لە parseIntـدا NumberFormatException فڕێ دەدەن؛ catchـەکە دەیانژمێرێت: ⁦12 + 7 + 30 + 9 = 58⁩.

Summaryکورتە

  • An exception is an object that a program throws when something goes wrong: a type, a message and a stack trace.
  • try holds the risky lines; a matching catch handles the exception and the program goes on; the rest of try is skipped.
  • Several catch blocks: specific first; | joins unrelated types; finally always runs.
  • Checked exceptions (such as IOException) must be caught or declared with throws; unchecked ones (RuntimeException, Error) usually mean a bug.
  • throw new IllegalArgumentException("...") refuses a bad value; your own exception class extends Exception.
  • A safe input loop catches, takes the bad token with next() and asks again; try-with-resources closes resources by itself.
  • کە فڕێی دەدات کاتێک شتێک هەڵە دەچێت: جۆرێک، پەیامێک و .
  • try دێڕە مەترسیدارەکان هەڵدەگرێت؛ catchـی گونجاو چارەسەر دەکات و بەردەوام دەبێت؛ باقیی try تێدەپەڕێنرێت.
  • چەند بەشێکی catch: تایبەت سەرەتا؛ | جۆری بێپەیوەندی پێکەوە دەبەستێت؛ finally هەمیشە جێبەجێ دەبێت.
  • (وەک IOException) دەبێت بگیرێن یان بە throws ڕابگەیەنرێن؛ نەپشکنراوەکان (RuntimeException، Error) زۆرجار واتای دەدەن.
  • throw new IllegalArgumentException("...") خراپ ڕەت دەکاتەوە؛ خۆت Exception extends دەکات.
  • سەلامەتی دەگرێت، پارچە خراپەکە بە next() دەبات و دووپاتە دەپرسێت؛ خۆی دادەخات.
Review questionsپرسیارەکانی پێداچوونەوە
What is the difference between throw and throws?جیاوازیی نێوان throw و throws چییە؟

throw throws one exception object now; throws in a method header says that the method may throw that type.

throw ئێستا یەک فڕێ دەدات؛ throws لە سەری دەڵێت ئەو لەوانەیە ئەو جۆرە فڕێ بدات.

When does finally not run?finally کەی جێبەجێ نابێت؟

Only if the JVM itself stops first, for example with System.exit. A caught, an uncaught exception or a return does not stop it.

تەنیا ئەگەر خودی JVM سەرەتا بوەستێت، بۆ نموونە بە System.exit. گیراو، نەگیراو یان return ڕێگری لێ ناکەن.

Why is FileNotFoundException checked but NullPointerException not?بۆچی FileNotFoundException پشکنراوە بەڵام NullPointerException نا؟

A missing file can happen in a correct program, so the caller should plan for it; a null method call is a bug to fix.

نەبوونی دەکرێت لە دروستیشدا ڕوو بدات، بۆیە دەبێت بیری لێ بکاتەوە؛ بانگکردنی لەسەر null کە دەبێت چاک بکرێت.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Files: Create, Write, Read and Deleteفایلەکان: دروستکردن، نووسین، خوێندنەوە و سڕینەوە

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.