异常 01:Error 和 Exception
异常体系结构
Java
把异常当作对象来处理,并定义一个基类 java.lang.Throwable
作为所有异常的超类。
在 Java API
中已经定义了许多异常类,这些异常类分为两大类,错误 Error
和 异常 Exception
。
Error
Error 类对象由 Java 虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关。
Java 虚拟机运行错误( Virtual MachineError ),当 JVM 不再有继续执行操作所需的内存资源时,将出现 OutOfMemoryError
。这些异常发生时,Java 虚拟机( JVM )一般会选择线程终止。
还有发生在虚拟机试图执行应用时,如类定义错误( NoClassDefFoundError )、链接错误( LinkageError )。这些错误是不可查的,因为它们在应用程序的控制和处理能力之外,而且绝大多数是程序运行时不允许出现的状况。
异常 02:捕获和抛出异常
异常处理的五个关键字
try、catch、finally、throw、throws
package opp.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // 监控异常
System.out.println(a/b);
}catch (ArithmeticException e){ // 捕获异常
System.out.println("b不能为0");
}finally { // 无论出没出现异常,都会运行 finally,处理善后工作
System.out.println("finally");
}
}
}
package opp.exception;
public class CatchManyException {
public static void main(String[] args) {
int a = 1;
int b = 0;
// 捕获多个异常:捕获范围由小到大
try { // 监控异常
System.out.println(a/b);
}catch (Exception e){ // 捕获异常
System.out.println("Exception");
}catch (Error e){
System.out.println("Error");
}catch (Throwable t){
System.out.println("Throwable");
} finally{ // 无论出没出现异常,都会运行 finally,处理善后工作
System.out.println("finally");
}
}
}
package opp.exception;
public class Test1 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// 快捷操作:Ctrl + Alt + T
try {
System.out.println(a/b);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
}
}
}
package opp.exception;
public class ThrowThrows {
public static void main(String[] args) {
try {
new ThrowThrows().test(1,0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}
// 假设在方法中,处理不了这个异常,就用 throws 上抛出异常
public void test(int a, int b) throws ArithmeticException{
if(b == 0){
throw new ArithmeticException(); // throw 主动抛出异常,一般在方法中使用
}
}
}
异常 03:自定义异常及经验小结
package opp.CustomException;
public class Test {
// 可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为:" + a);
if(a > 10){
throw new MyException(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(1);
} catch (MyException e) {
System.out.println("MyException=>" + e);
}
}
}
package opp.CustomException;
// 自定义异常类
public class MyException extends Exception{
private int detail;
public MyException(int a) {
this.detail = a;
}
@Override
public String toString() {
return "MyException{" + detail + '}';
}
}