5-异常
异常:运行时的错误(一旦出现异常,整个程序崩溃)
- 1. 异常体系结构
Throwable 超类/根类
Error类:不可避免的非程序性错误(JVM错误、内存溢出。。。)
Exception类:可避免的程序性错误,指异常(RuntimeException运行时异常,非运行时异常) - 2. 常见的异常类
- 运行时异常
- 算术异常 ArithmeticException 如:int i = 10/0;
- 下标越界 IndexOutOfBoundsException 如:String[] ss = {"a"}; System.out.println(ss[1]);
- 空指针异常 NullPointerException 如:String s = null; System.out.println(s.toString());
- 输入异常 InputMismatchException
- 类转换异常 ClassCastException 如:Person p = new Student(); Teacher t = (Teacher)p;
- IOException
- SQLException
- NetException
- 3. 异常处理(三个语句块,try、catch、finally)
目的:提高程序的健壮性,程序出错时友好的提示
程序某环节的出错不能导制整个程序的崩溃
Scanner sc = null;
try { // 监控异常,如果没出异常就不会执行catch内的代码
sc = new Scanner(System.in);
System.out.println("请输入一个数:");
int i = sc.nextInt();
System.out.println(i);
} catch(Exception e) { // 捕获异常,只有当try里的代码出了异常才会被执行
e.printStackTrace(); // 打印异常信息
} finally { // 最终,不管出不出现异常都会被执行,一般做资源的回收清理事项
sc.close();
}
- try.catch.finally是异常的一个组合,以下注意:
- 不能单独使用
- 可以是两个组合,但其中必有一个try
- catch可以出现多个对应不同的异常子类,但通常会在最后catch里来一个通用的Exception
- 4. 多catch处理
- 5. 方法的异常申明
public void 方法名(参数列表) throws Exception{
throw new Exception("异常信息"); // 手动抛出异常(非系统性的异常)
手动抛出异常 throw new Exception("异常信息"); 必须存在具有异常声明的方法内
}
throws Exception声明的方法在调用时必须做异常处理
try{
方法名(参数列表);
} - 6.throws 和 throw 的区别
1.throws表示方法的异常声明,调该方法的时候必须进行异常处理
2.throw表示手动抛异常,非系统性的
爱你爱你爱你爱你爱你昕宝贝

浙公网安备 33010602011771号