جاوا امتحان کنید و بگیرید(Java try and catch)

عبارت try به شما امکان می دهد بلوکی از کد را تعریف کنید.
برای خطاها در حین اجرا آزمایش شد.


عبارت catch به شما امکان می دهد بلوکی از کد را تعریف کنید
اگر خطایی در بلوک try رخ داد، اجرا شود.


کلمات کلیدی try و catch
دو به دو بیایید:




Syntax


try {
  //  Block of code to try
}
catch(Exception e) {
  //  Block of code to handle errors
}


مثال زیر را در نظر بگیرید:



This will generate an error, because myNumbers[10] does not exist.



public class MyClass {
  public static void main(String[ ] args) {
    int[] myNumbers = {1, 2, 3};
    System.out.println(myNumbers[10]); // error!
  }
}

The output will be something like this:




Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
       
at MyClass.main(MyClass.java:4)




اگر خطایی رخ داد، می‌توانیم از try...catch برای دریافت خطا و اجرای کدی برای رسیدگی به آن استفاده کنیم:



مثال


public class MyClass {
  public static void main(String[ ] args) {
    try {
      int[] myNumbers = {1, 2, 3};
      System.out.println(myNumbers[10]);
    } catch (Exception e) {
      System.out.println("Something went wrong.");
    }
  }
}

The output will be:




Something went wrong.