1z-808复习 第6章

Exceptions

  • 区分checked excpetion,unchecked exception,Errors
  • Create a try-catch block and determine how exceptions alter normal program flow
  • Describe the advantages of Exception handling
  • Create and invoke a method that throws an exception
  • Recognize common exception classes (such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException)

Understanding Exceptions

The Role of Exceptions

Exception是Java在处理中遇到的问题。

Understanding Exception Types

所有Exceptions或Errors的父类是Throwable。 Error是指非常严重并且程序中无法复原的错误。 Runtime exceptions are also known as unchecked exceptions.
checked Exception是指所有不是从RuntimeException派生出来的Exception。
Java中有一条规则叫“handle or declare rule”,是指对于checked exception
要么有handle的代码,要么有在method signature 里declare的代码。

Throwing an Exception

第一种方法是写的代码本身有错,执行时

Using a try Statement

try后面不能少大括号,即使只有一条语句。
不能少catch语句。

Adding a finally Block

finally里面的语句,无论是否发生Exception,都会被执行。 finally一般用在最后关闭文件句柄,关闭数据库连接。

Catching Various Types of Exceptions

可以写多个catch块,但是如果一个都执行不到,会出compile error,
也就是说在try块中一定要保证会出catch的Exception。

只有先子类Exception,再父类Exception才有可能被执行到。 反过来就会发生上面所说的执行不到的CompileError。

Throwing a Second Exception

Recognizing Common Exception Types

Runtime Exceptions

Checked Exceptions

Errors

Calling Methods That Throw Exceptions

Subclasses

在子类中方法override时,不可以增加父类中没有declare的Exception。
设想一下如果增加了,会有什么问题。 可以写调用父类的方法,并且不处理任何Exception。 通过多态性来考虑,如果子类也有同样的方法,也可以传入子类。 这时候应该处理还是不处理错误就变得不明了。

Printing an Exception

public static void main(String[] args) {
    try {
        hop();
    } catch (Exception e) {
        System.out.println(e);
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
private static void hop() {
    throw new RuntimeException("cannot hop");
}

上面是打印Exception的三种方法。

Summary

Exam Essentials

Review Questions