java将异常分为两种,checked exception和unchecked exception(通常指runtimeException)。java
checked exception:不是调用者非法使用或传入不正确参数形成的异常,运行时遇到此类异常须要调用者根据状况做出反应,捕获后程序能够继续运行,代码中必须显示捕获,若是抛出此类异常也须要在函数名后显示加入throws关键字数组
public static void checkedExceptionMaker() throws Exception{ throw new Exception("checkExceptionMaker exception"); }
unchecked exception:程序运行期间,因调用者不正确使用致使的异常发生,此时可使用运行时异常,并使得程序遇到此异常时,被终止,可能抛出unchecked exception的函数无需指定throws异常类型tcp
public static void runtimeExceptionMaker() { throw new RuntimeException("runtimeExceptionMaker 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 }
运行结果:spa
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的代码没有被执行。code
/*何时用check exception,何时须要unchecked exception?*/blog
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来结束当前的程序。