异常 - 图1

Try-With-Recourse

try-with-recourse的写法相对于try-catch-finally更简洁,对比如下:

  • try-catch-finally

    1. import java.io.*;
    2. public class MessyExceptions {
    3. public static void main(String[] args) {
    4. InputStream in = null;
    5. try {
    6. in = new FileInputStream(new File("MessyExceptions.java"));
    7. int contents = in.read();
    8. } catch(IOException e) {
    9. // Handle the error
    10. } finally {
    11. if(in != null) {
    12. try {
    13. in.close();
    14. } catch(IOException e) {
    15. // Handle the close() error
    16. }
    17. }
    18. }
    19. }
    20. }
  • try-with-recourse

    1. import java.io.*;
    2. public class TryWithResources {
    3. public static void main(String[] args) {
    4. try(
    5. InputStream in = new FileInputStream(new File("TryWithResources.java"))
    6. ) {
    7. int contents = in.read();
    8. // Process contents
    9. } catch(IOException e) {
    10. // Handle the error
    11. }
    12. }
    13. }

    显然try-with-recourse简洁得多,它会按照申明顺序自动释放()中的资源。

    • 工作原理

try-with-resources 定义子句中创建的对象(在括号内)必须实现 java.lang.AutoCloseable 接口,这个接口只有一个方法:close()。当在 Java 7 中引入 AutoCloseable 时,许多接口和类被修改以实现它,如:Stream 对象 。
Java 5 中的 Closeable 已经被修改,修改之后的接口继承了 AutoCloseable 接口。所以所有实现了 Closeable 接口的对象,都支持了 try-with-resources 特性。

  • 注意
    1. catch 块中,看不到 try-with-recourse 声明中的变量;
    2. try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得;
    3. try-with-recourse 中定义多个变量时,由反编译可知,关闭的顺序是从后往前。

自定义异常

  1. package com.cq.common.exception;
  2. /**
  3. * 自定义运行时异常类
  4. * 一般在业务层逻辑出现问题时抛出
  5. */
  6. public class MyException extends RuntimeException {
  7. /**
  8. * 错误状态码
  9. * - 暂时用不着
  10. */
  11. private Integer errorCode;
  12. /**
  13. * 错误信息
  14. */
  15. private String errorMsg;
  16. public MyException(String errorMsg) {
  17. super(errorMsg);
  18. this.errorMsg = errorMsg;
  19. }
  20. public MyException(Throwable trace) {
  21. super(trace);
  22. }
  23. public MyException(String errorMsg, Throwable trace) {
  24. super(errorMsg, trace);
  25. }
  26. public String getErrorMsg() {
  27. return this.errorMsg;
  28. }
  29. }