当程序遇到了异常,可以选择两种处理方式:捕获或者向上抛出。
当调用了一个抛出异常的方法时,调用位置可以能不做处理继续向上抛出也可以捕获异常自行处理。
调用抛出异常的方法时不做处理,继续向上抛出:
public class Test2_Exception {
public static void main(String[] args) throws Exception {//继续向上抛出异常
method3();
}
//抛出异常:在方法上加throws 异常类型1,异常类型2,异常类型3
private static void method3()throws Exception{//向上抛出异常
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
System.out.println(a/b);
}
}
调用抛出异常的方法时,捕获异常自行处理:
public class Test2_Exception {
public static void main(String[] args) {
try {
method3();// 抛出异常
} catch (Exception e) {//捕获异常自行处理
System.out.println("执行失败。。");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//抛出异常:在方法上加throws 异常类型1,异常类型2,异常类型3
private static void method3()throws Exception{//向上抛出异常
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
System.out.println(a/b);
}