qaq
异常
- 最上层父类:
Exception
- 分为:编译时异常、运行时异常
- 编译时异常:直接继承于
Exception,编译阶段就会错误提示(java文件
-> 字节码文件)
- 运行时异常:
RuntimeException本身和子类,运行时出错误提示(字节码文件
-> 运行结果)
异常的处理方式
JVM默认处理方式
- 把异常名字、异常原因、异常出现位置以红色字体输出在控制台
- 程序中止
自己处理
1 2 3 4 5 6 7
| int[] arr = {1, 2, 3}; try { System.out.println(arr[5]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("索引越界"); } System.out.println("Hello");
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| int[] arr = {1, 2, 3, 4};
try { System.out.println(arr[10]); System.out.println(2/0); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("索引越界"); } System.out.println("Hello");
|
若try中可能遇到多个异常,写多个catch与之对应。
- 注意:如果这些异常中存在父子关系,父类写下面
- 多个
catch也不能同时捕获多个异常,碰到第一个异常就退出了
JDK7之后,可以在catch中捕获多个种类的异常
1 2 3 4 5
| try { } catch(ArrayIndexOutOfBoundsException | ArithmeticException e) { }
|
try中遇到的异常没被捕获,采用JVM默认方法处理
异常的常见方法
Throwable的成员方法
public void printStackTrace():把异常信息输出在控制台,不会停止程序运行
public String toString():返回这个可抛出的简短描述
public String getMessage():返回此throwable的详细消息字符串
抛出异常
1 2 3
| public void method() throws 异常1, 异常2... { ... }
|
1 2 3 4 5 6 7 8 9
| public static int getMax(int[] arr) { if(arr == null) { throw new NullPointerException(); } if(arr.length == 0) { throw new ArrayIndexOutOfBoundsException(); } ... }
|
自定义异常
主要是写自定义的名字
1 2 3 4 5 6 7
| public class NameFormatException extends RuntimeException { public NameFormatException() { } public NameFormatException(String message) { super(message); } }
|
try catch finally
JDK7:IO流中捕获异常的写法
只有实现了AutoCloseable接口的类才能在小括号中创建对象
1 2 3 4 5 6 7 8
| public static void main(String[] args) { try(FileInputStream fis = new FileInputStream(""); FileOutputStream fos = new FileOutputStream("")) {
} catch(IOException e) { e.printStackTrace(); } }
|
资源自动释放
JDK9
1 2 3 4 5 6 7 8 9
| public static void main(String[] args) throws FileNotFoundException { FileInputStream fis = new FileInputStream(""); FileOutputStream fos = new FileOutputStream(""); try(fis;fos) { } catch(IOException e) { e.printStackTrace(); } }
|