异常类型
检查性异常:例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略
运行时异常:运行时异常是可能被程序员避免的异常。运行时异常可以在编译时被忽略
捕获异常
1 2 3 4 5 6 | try { // 程序代码 }catch(ExceptionName e) { //Catch 块 } |
try后面可以接多个catch块
e.g.
1 2 3 4 5 6 7 8 9 10 11 | public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); System.out.println("Hello world!"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } |
输出:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
因此不执行抛出异常之后的语句(没有输出Hello world!)
throws/throw关键字
throws写在方法签名的尾部,用于抛出该方法可能导致的异常类交给上一级处理。可抛出多个异常(用逗号分隔)
returnType method_name(paramList) throws Exception 1, Exception2, … {…}
throw直接抛出一个异常,可在try中交给catch处理,也可以通过throws抛给上一级。throw之后的语句不会再执行
throw new xxxException("异常提示信息");
finally关键字
可接在catch块后,执行try之后没有执行的代码
1 2 3 4 5 6 7 | try{ // 程序代码 }catch(异常类型 异常的变量名){ // 程序代码 }finally{ // 程序代码 } |
声明自定义异常
所有异常都必须是 Throwable 的子类
如果希望写一个检查性异常类,则需要继承 Exception 类
如果希望写一个运行时异常类,那么需要继承 RuntimeException 类
class MyException extends Exception {...}
注:示例见Intellij