Java: Exceptions - Try...Catch

try and catch

确切的说这应该是Exception。因为Error是指Java虚拟机无法解决的严重问题,如stack溢出,堆溢出...

 

 Use try and catch: 可以写多个catch来捕捉不同的exception类型

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:

即使try有return或catch中有异常,finally也会被运行

如果是return,finally 会在return前被执行

我们一般使用finally来关闭数据库连接,输入输出流等

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)

 

Structure of Throwable

 

 Examples of runtime exception

 

 

 

 

 

 

 

输入不匹配抛出,当输入的类型不是Int是就会抛出异常

 

 

 

 

Exception e

e.getMessage();

e.printStackTrace(); // 包含message,并且还有详细的说明, console会打印这样的东西

 

posted @ 2022-11-27 20:08  小白冲冲  阅读(23)  评论(0编辑  收藏  举报