异常处理:
方式一:捕获处理
捕获处理的格式:
try{
可能发生异常的代码
}catch(捕获的异常类型 变量名){
处理异常的代码
}
方式二:抛出处理
public class CaptureException
{
public static void main(String[] args)
{
div(3,0);
}
public static void div(int a,int b){
int c = 0;
try{
c = a/b;
}catch(ArithmeticException e){
System.out.println("异常处理 ");
System.out.println("toString:"+e.toString());
}
System.out.println("c = "+c);
}
}
一个try块后面可以跟多个catch块,但是捕获的异常类型必须从小到大开始捕获异常。
public class CaptureException
{
public static void main(String[] args)
{
int[] arr = null;
div(3,2,arr);
}
public static void div(int a,int b,int[] arr){
int c = 0;
try{
c = a/b;
System.out.println("数组的长度; "+arr.length);
}catch(ArithmeticException e){
System.out.println("异常处理 ");
System.out.println("toString:"+e.toString());
}catch(NullPointerException e){
System.out.println("出现了空指针异常 ");
}
System.out.println("c = "+c);
}
}