第九章: Error Handling with Exceptions
-- badly formed code will not be run
当发生异常的时侯,它会跳出当前的运行环境,把问题交给上一层运行环境。另外异常机制让程序的执行代码和错误处理代码分离,增强了程序的可读性和维护性。
1、 Basic exceptions
if(t == null)
throw new NullPointerException();
2、Exception arguments
throw new NullPointerException("t = null");
3、Catching an exception
// Code that might generate exceptions
} catch(Type1 id1) { //Exception handlers
// Handle exceptions of Type1
} catch(Type2 id2) {
// Handle exceptions of Type2
} catch(Type3 id3) {
// Handle exceptions of Type3
}
3、 Creating your own exceptions
class MyException extends Exception {
public MyException() {}
public MyException(String msg) { super(msg); }
}
4、 The exception specification(异常说明)
void f() throws TooBig, TooSmall, DivZero { //...告诉调用你方法的客户程序员,你定义的方法可能抛出哪些异常,因此调用的人就知道编写相应的处理程序来处理潜在的异常,但是你可以撒谎申明你并不真正抛出的异常。
5、 Catching any exception
catch(Exception e) {
System.err.println("Caught an exception");
}
// Demonstrating the Exception Methods.
import com.bruceeckel.simpletest.*;
public class ExceptionMethods {
private static Test monitor = new Test();
public static void main(String[] args) {
try {
throw new Exception("My Exception");
} catch(Exception e) {
System.err.println("Caught Exception");
System.err.println("getMessage():" + e.getMessage());
System.err.println("getLocalizedMessage():" +
e.getLocalizedMessage());
System.err.println("toString():" + e);
System.err.println("printStackTrace():");
e.printStackTrace();
}
monitor.expect(new String[] {
"Caught Exception",
"getMessage():My Exception",
"getLocalizedMessage():My Exception",
"toString():java.lang.Exception: My Exception",
"printStackTrace():",
"java.lang.Exception: My Exception",
"%% /tat ExceptionMethods.main//(.*//)"
});
}
} ///:~
6、 Rethrowing an exception
catch(Exception e) {
System.err.println("An exception was thrown");
throw e;
// throw e.fillInStackTrace();
}
Rethrowing an exception causes it to go to the exception handlers in the next-higher context. Any further catch clauses for the same try block are still ignored. In addition, everything about the exception object is preserved, so the handler at the higher context that catches the specific exception type can extract all the information from that object.
you can also do by calling fillInStackTrace( ), which returns a Throwable object that it creates by stuffing the current stack information into the old exception object.
7、 Standard Java exceptions
There are two general types of Throwable objects (“types of” = “inherited from”). Error represents compile-time and system errors that you don’t worry about catching. Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and run-time accidents
8、 RuntimeException
--They’re always thrown automatically by Java and you don’t need to include them in your exception specifications.它们会自动得到处理。
9、 Performing cleanup with finally--the finally clause always runs
import com.bruceeckel.simpletest.*;
class ThreeException extends Exception {}
public class FinallyWorks {
private static Test monitor = new Test();
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.err.println("ThreeException");
} finally {
System.err.println("In finally clause");
if(count == 2) break; // out of "while"
}
}
monitor.expect(new String[] {
"ThreeException",
"In finally clause",
"No exception",
"In finally clause"
});
}
} ///:~
10、 Exception restrictions(加在异常上的限制)
复写方法的时侯,你只能抛出这个方法在基类中声明的异常。(只能申明和抛出不比父类版本中申明的异常多的异常)
- Handle problems at the appropriate level. (Avoid catching exceptions unless you know what to do with them).
- Fix the problem and call the method that caused the exception again.
- Patch things up and continue without retrying the method.
- Calculate some alternative result instead of what the method was supposed to produce.
- Do whatever you can in the current context and rethrow the same exception to a higher context.
- Do whatever you can in the current context and throw a different exception to a higher context.
- Terminate the program.
- Simplify. (If your exception scheme makes things more complicated, then it is painful and annoying to use.)
- Make your library and program safer. (This is a short-term investment for debugging, and a long-term investment for application robustness.)