本文实例讲述了Java基础之异常处理操作。分享给大家供大家参考,具体如下:
示例代码:
public class ExecDemo {
public static void main(String[] args) {
int[] nums = new int[4];
System.out.println("before the exception:");
try { //try代码块 try catch代码块可以嵌套
try{
nums[7] = 10; //数组越界
System.out.println("no exception:");
}catch(ArithmeticException e){
e.printStackTrace();
}
}catch(ArithmeticException e) { //catch代码块 多个catch块
e.printStackTrace(); //打印异常信息
}catch(ArrayIndexOutOfBoundsException e){ // 捕获数组越界错误 捕获子类异常
e.printStackTrace();
}catch(Throwable e){ //捕获超类异常 Throwable是所有异常的超类
e.printStackTrace();
}
System.out.println("after the exception");
}
}
抛出异常:
public class ThrowDemo {