一、异常的定义
异常是不确定的、非正常情况的事件。Java的异常就是Java按照面向对象的思想将问题进行对象封装。这样就方便于操作问题以及处理问题。
二、异常的结构
1.Exception与error的差别
先看api上怎么写的:
Throwable的说明
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.
Error的说明
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
Exception的说明
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
从中可以看出Error是程序无法捕获处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。
而Exception是程序本身能够处理的异常。
2.Exception的结构
2.1 RuntimeException 运行时异常
ArithmeticException:
public static void main(String[] arg){
int b=0;
System.out.println(1/b);//除0
}
ArrayIndexOutOfBoundsException:
public static void main(String[] arg){
int b[]=new int[5];
System.out.println(b[-1]);//数组越界
}
NullPointerException:
public static void main(String[] arg){
String b=null;
System.out.println(b.getBytes(StandardCharsets.UTF_8));//空指针
}
NumberFormatException:
public static void main(String[] arg){
String str = "1234abcf";
System.out.println(Integer.parseInt(str));//数字错误
}
2.2CheckedException 已检查异常
所有不是RuntimeException的异常,统称为Checked Exception,即“已检查异常”。反过来来说,除了Checked Exception,就是unchecked。如IOException、SQLException等以及用户自定义的Exception异常。 这类异常在编译时就必须做出处理,否则无法通过编译。
三、两种方式
1.catch
try {
…
} catch(Exception e) {
}
2.throws
四、throws与throw
throws:
用在方法声明处,其后跟着的是异常类的名字
表示此方法会抛出异常,需要由本方法的调用者来处理这些异常
throw:
用在方法的内部,其后跟着的是异常对象的名字
表示此处抛出异常,由方法体内的语句处理