异常处理
try {
// 代码块
}catch(Exception e) {
// 当代码块中出现 Exception 时才会执行此处代码块
e.printStackTrace();
} finally {
// 不管代码块中是否出现异常,此处代码都会执行
}
throws 用于在声明方法的时候明确指出调用方法可能会出现的错误
throw 主要用来触发异常
throw new ArrayIndexOutOfBoundsException();
自定义异常处理
class CustomException extends Exception
{
public void printStackTrace() {
System.out.println("CustomException -->" + "出现异常错误");
}
}
public class Main {
public void print() throws CustomException {
int[] numbers = {1, 2, 3};
throw new CustomException();
}
public static void main(String[] args) {
Main m = new Main();
try {
m.print();
}catch (CustomException e) {
e.printStackTrace();
}
}
}