public class ExceptionDemo {
public static void main(String[] args) {
System.out.println("1.程序开始运行~");
try{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
System.out.println("2.计算数学公式 " + x/y);
}catch (ArithmeticException e) {
e.printStackTrace();
// }catch (ArrayIndexOutOfBoundsException e){
// e.printStackTrace();
// }catch (NumberFormatException e){
// e.printStackTrace();
}finally {
System.out.println("F 不管是否出现异常,我都会执行");
}
System.out.println("3.计算结束");
}
}
// javac -encoding UTF-8 ExceptionDemo.java
// 第一种异常:没有输入参数,异常未被catch,finally会执行,注释内容为3的这行不会被执行
//1.程序开始运行~
// F 不管是否出现异常,我都会执行
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
// at ExceptionDemo.main(ExceptionDemo.java:5)
// 第二种异常,输入参数类型不对,异常未被catch,finally会执行,注释内容为3的这行不会被执行
//1.程序开始运行~
// F 不管是否出现异常,我都会执行
// Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
// at java.lang.NumberFormatException.forInputString(Unknown Source)
// 第三种异常,输入 10 0 ,异常被catch,finally会执行,注释内容为3的这行会被执行
//1.程序开始运行~
// java.lang.ArithmeticException: / by zero
// at ExceptionDemo.main(ExceptionDemo.java:7)
// F 不管是否出现异常,我都会执行
// 3.计算结束
try...catch...finally 用法示例
最新推荐文章于 2022-08-09 10:24:00 发布