Java异常的使用

1.exception的分类

java将异常分为两种,checked exception和unchecked exception(一般指runtimeException)。

checked exception:不是调用者非法使用或传入不正确参数造成的异常,运行时遇到此类异常需要调用者根据情况作出反应,捕获后程序可以继续运行,代码中必须显示捕获,如果抛出此类异常也需要在函数名后显示加入throws关键字

public static void checkedExceptionMaker() throws Exception{
    throw new Exception("checkExceptionMaker exception");
}

unchecked exception:程序运行期间,因调用者不正确使用导致的异常发生,此时可以使用运行时异常,并使得程序遇到此异常时,被终止,可能抛出unchecked exception的函数无需指定throws异常类型

public static void runtimeExceptionMaker() { 
    throw new RuntimeException("runtimeExceptionMaker exception"); 
}

2.exception的捕获

checked exception需要显示捕获,否则会编译出错,而unchecked exception是可选地捕获,万一不捕获就会沿函数栈(调用函数轨迹)往上抛出,最终终止程序。

 1 public static void main(String[] argv) {
 2 
 3         try {
 4             checkedExceptionMaker();
 5             System.out.println("pass checked exception");
 6         } catch (Exception e) {
 7             e.printStackTrace();
 8         }
 9         System.out.println("program is still running...");
10         runtimeExceptionMaker();
11 
12         System.out.println("program is done");
13 
14     }

运行结果:

java.lang.Exception: checkExceptionMaker exception
    at edu.xhyzjiji.cn.exception_demo.ExceptionClassify.checkedExceptionMaker(ExceptionClassify.java:26)
    at edu.xhyzjiji.cn.exception_demo.ExceptionClassify.main(ExceptionClassify.java:13)
Exception in thread "main" java.lang.RuntimeException: runtimeExceptionMaker exception
    at edu.xhyzjiji.cn.exception_demo.ExceptionClassify.runtimeExceptionMaker(ExceptionClassify.java:30)
    at edu.xhyzjiji.cn.exception_demo.ExceptionClassify.main(ExceptionClassify.java:19)
program is still running...

注意行5,12的代码没有被执行。

/*什么时候用check exception,什么时候需要unchecked exception?*/

checked exception是对接口调用者(后面简称调用者)输入参数可预知的异常进行检查, 比如除数为0,某些必要参数为null,打开了不存在的文件之类,这些问题是由调用者引入,并非接口源码的漏洞,我们就可以大胆使用checked exception,以告知调用者可能存在的输入问题,调用者以try-catch方式捕获这些异常,并根据异常类型将程序引导到正常流程中去。

unchecked exception可能是接口本身问题而导致异常的出现,比如数组越界访问,因端口号被占用使得创建tcp客户端失败,这些异常可能存在以下特点:
1.接口源码本身有问题;2.异常产生使后续程序无法运行,这时候应该终止程序并让接口开发者修改潜在问题,重新发布接口,这时候我们可以选用unchecked exception。


 /*unchecked exception是否需要try-catch*/

有时候为了程序不因此崩溃,需要对unchecked exception也进行try-catch,这依赖于对接口源码一定的熟悉程度,但是由于unchecked exception的发生,调用者无法引导程序归入正常流程,所以即使try-catch捕获到异常,后续的调用也会继续抛出异常,try-catch的意义就不大了,而且会令我们的代码满布try-catch代码块。

温和的做法是我们可以选择try-catch可能发生的unchecked exception,并重试数次或累计抛出次数,如果依然得不到解决,我们自己再抛出一个runtime exception来结束当前的程序。

3.异常/捕获的嵌套

4.继承exception,利用code减少catch数量

5.exception捕获原理

原文地址:https://www.cnblogs.com/xhyzjiji/p/6159506.html