概述
Java 的异常是 class 下面的图表示了 Java 异常 的家族体系
可以看到,所有的异常都是继承于 Throwable 类, 分为两大派系,一个是 Error ,一个是 Exception , 其中 Error 表示我们无能为力的错误,这部分我们不用管,我们需要捕捉的是 Exception ,当然 Exception 又分为两类, RuntimeException 的异常 和 非 **RuntimeException** 的异常
其区别:非 RunTimeException ,受检查异常。必须要开发者解决以后才能编译通过,一般使用其子类,也就是 Java 内部已经帮你想好的,你需要解决的一些常见的异常, 解决的方法有两种:
1:throw到上层,
2,try-catch处理。
RunTimeException :运行时异常,又称不受检查异常,因为不受检查,所以在代码中可能会有 RunTimeException 时Java编译检查时不会告诉你有这个异常,但是在实际运行代码时则会暴露出来,比如经典的1/0,空指针等。 通常用于我们自定义异常的时候做为父类,也就是一些业务逻辑异常。
捕获异常
我们一般使用 try...catch 进行捕获异常,格式如下
try{...}catch(IOException e){...}catch(FileNotFoundException e){...}finally{...}
抛出异常
有些异常我们不知道如何处理,我们可以先往上层抛,等到真正调用的时候再处理。这里我们使用 throws 来抛出异常
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ExceptionTest {public static void main(String[] args) {// java.io.FileNotFoundException: test.log (The system cannot find the file specified)// 输出 don't have this filetry{readFile("test.log");}catch (IOException e){//e.printStackTrace();System.out.println("don't have this file");}}public static void readFile(String fileName) throws IOException {BufferedReader in = new BufferedReader(new FileReader(fileName));String str;while ((str = in.readLine()) != null) {System.out.println(str);}System.out.println(str);}}
自定义异常
我们定义业务异常的时候,一般选择从 RuntimeException 里面派生出一个类,然后所有的业务异常继承这个类
public class CustomRuntimeException {public static void main(String[] args) {try{// 如何用?Business b = new Business();b.test();/*** 业务逻辑异常* BussinessException: 业务逻辑出现异常* at Business.test(CustomRuntimeException.java:35)* at CustomRuntimeException.main(CustomRuntimeException.java:12)*** */}catch (BussinessException e){e.printStackTrace();}}}class BaseException extends RuntimeException{public BaseException(String msg) {super(msg);}}class BussinessException extends BaseException{public BussinessException(String msg){super(msg);System.out.println("业务逻辑异常");}}// 新建一个使用的类class Business{public void test(){throw new BussinessException("业务逻辑出现异常");}

