异常

  1. 程序中的问题分类

a) 警告 warning

  1. 变量声明赋值未使用
  2. 导入了没有使用的包
  3. 不影响程序的正常运行

b) 错误  error

  1. 语法错误 程序无法编译

c) 异常  Excetpion

  1. 运行期错误 在控制台打印信息  程序终止执行
  2. 所有的异常都继承自  Exception

 

  2.异常的处理

a) 主动处理

  1. try{} 异常的监测语句块  有且必须出现一次, 建议只将可能发生异常的语句放在该语句块中
  2. catch(异常类型 对象名){} 捕获和处理异常的语句块,可以直接打印系统异常(异常对象名.printStactranc()),也可以自行处理

Catch可以并列出现多次 ,父类异常放在最后捕获

Iii.  finally{} 无论是否出现异常都必须执行的代码块  finallycatch至少要出现一

b) 抛出异常

  1. throws Exception  自己不处理异常 交给自己的调用者处理,在方法参数列表后抛出

  3.代码演示:

public class ExceptionDemo {

public static void demo() {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个整数:");
try {
int num = input.nextInt();// 可能出现输入数据类型不匹配InputMismatchException
int[] arr = { 1, 2, 3, 5, 4, 6, 7 };
for (int i = 0; i < arr.length; i++) {// 可能出现数组下标越界ArrayIndexOutOfBoundsException
System.out.println(arr[i] / num);// 可能出现分母不能为0异常(只在整型运算时,分母不能为0。浮点型运算时分母可以为0,算出的结果是无限大infinity)
}
System.out.println("大家好");
//System.exit(0);//退出程序,不会之后的代码,需要注释
} catch (InputMismatchException i) {
System.out.println("输入数据类型不匹配");
} catch (ArrayIndexOutOfBoundsException a) {
System.out.println("数组下标越界");
}catch(Exception e){
System.out.println("分母不能为0");
}finally{
System.out.println("大家好");
}
}

public static void main(String[] args) {
demo();
}

}

原文地址:https://www.cnblogs.com/dopaer/p/6605950.html