《Java编程思想》读书笔记(五)

wshunli
2017-12-04 / 0 评论 / 57 阅读 / 正在检测是否收录...

《Java编程思想》读书笔记 —— 异常处理。

第12章 通过异常处理错误

Java的基本理念是“结构不佳的代码不能运行”。

Java异常

Java 中的异常处理都是围绕着 try-catch-finally, throw, throws 这几个展开的,也就是:

try-catch-finally:捕获异常并处理。
throw:遇到错误的时候抛出一个异常。
throws:声明一个方法可能抛出的异常(所有可能抛出的异常都需要声明)。

class ThreeException extends Exception {}
public class FinallyWorks {
  static int count = 0;
  public static void main(String[] args) {
    while(true) {
      try {
        // Post-increment is zero first time:
        if(count++ == 0) throw new ThreeException();
        System.out.println("No exception");
      } catch(ThreeException e) {
        System.out.println("ThreeException");
      } finally {
        System.out.println("In finally clause");
        if(count == 2) break; // out of "while"
      }
    }
  }
}
/* Output:
ThreeException
In finally clause
No exception
In finally clause
*/

throw 与 throws 的差别

throw 是语句抛出一个 Throwable 类型的异常,总是出现在函数体中;程序会在 throw 语句之后立即终止。

如果一个方法可能会出现异常,但没有能力处理这种异常,可以在方法声明处用 throws 子句来声明抛出异常;
throws 语句用在方法定义时声明该方法要抛出的异常类型,多个异常可使用逗号分割。

f() throws Exception1, Exception2, Exception3, ... {
    ...
}

例如:

import java.lang.Exception;

public class TestException {
    public int div(int x, int y) throws MyException {
        if (y == 0) {
            throw new MyException("除数不能为0");
        }
        return (int)(x/y);
    }

    public static void main(String[] args) {
        int x = 1;
        int y = 0;
        try {
            int result = div(x, y);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}

//自定义异常类
class MyException extends Exception {
    String message;
    public MyException(String ErrorMessage) {
        message = ErrorMessage;
    }
    public String getMessage() {
        return message;
    }
}

参考资料
1、《Java编程思想》读书笔记 第十二章 通过异常处理
https://zhuanlan.zhihu.com/p/25935822
2、Java编程思想第四版读书笔记——第十二章 通过异常处理错误 - CSDN博客
http://blog.csdn.net/severusyue/article/details/51780879
3、Java 异常处理
https://zhuanlan.zhihu.com/p/24043941

0

评论 (0)

取消