首页 > 编程语言 >Java: Exceptions - Try...Catch

Java: Exceptions - Try...Catch

时间:2022-11-27 20:24:03浏览次数:57  
标签:try System Try catch Catch Exceptions Main public out

try and catch

 

 Use try and catch:

public class Main {
  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.");
    }
  }
}

// Outputs:
Something went wrong.

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

public class Main {
  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.");
    } finally {
      System.out.println("The 'try catch' is finished.");
    }
  }
}

// Outputs:
Something went wrong.
The 'try catch' is finished.

The throw keyword

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":

public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}

// Outputs:
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
        at Main.checkAge(Main.java:4)
        at Main.main(Main.java:12)

 

标签:try,System,Try,catch,Catch,Exceptions,Main,public,out
From: https://www.cnblogs.com/ShengLiu/p/16930504.html

相关文章