-
java异常处理包括两种代码块。一种是try…catch,一种是try…catch…finally。
-
tyr-catch**
把有可能产生异常的代码放到try中,如果try中的代码产生异常,由catch捕获。语法:
try {可能产生异常的代码
} catch(异常类型 e){
异常处理
}
-
try…catch三种运行情况
3.1【1】没有发生异常,程序正常执行
【2】出现异常,catch进行捕获,进行异常处理,处理完后,进行后续程序的运行
【3】出现异常,由于异常类型不匹配,未能捕获异常,程序终止
-
多重catch
可以为try代码书写多个catch用于捕获多个具体的异常。
书写时:子类在上
public class Test01 {
public static void main(String[] args) {Scanner sc = new Scanner(System.in); System.out.println("请输入被除数:"); try { int num1 = sc.nextInt(); System.out.println("请输入除数:"); int num2 = sc.nextInt(); int r = num1 / num2; System.out.println(r); }catch (InputMismatchException e) { System.out.println("输入数据有误"); }catch(ArithmeticException e) { System.out.println("除数不能为0"); }catch(Exception e) { System.out.println("未知异常"); } System.out.println("程序正常结束!");
}
}