java中的异常

java异常

  Notice that all exceptions descend from Throwable, but the hierarchy immediately splits into two branches: Error and Exception.

  The Error hierarchy describes internal errors and resource exhaustion situations inside the Java runtime system. You should not throw an object of this type. There is little you can do if such an internal error occurs, beyond notifying the user and trying to terminate the program gracefully. These situations are quite rare.

When doing Java programming, you focus on the Exception hierarchy. The Exception hierarchy also splits into two branches: exceptions that derive from RuntimeException and those that do not.

The general rule is this: A RuntimeException happens because you made a programming error. Any other exception occurs because a bad thing, such as an I/O error, happened to your otherwise good program.

Exceptions that inherit from RuntimeException include such problems as

• A bad cast

• An out-of-bounds array access

• A null pointer access

Exceptions that do not inherit from RuntimeException include

• Trying to read past the end of a file

• Trying to open a file that doesn’t exist

• Trying to find a Class object for a string that does not denote an existing class

  The rule “If it is a RuntimeException, it was your fault” works pretty well. You could have avoided that ArrayIndexOutOfBoundsException by testing the array index against the array bounds. The NullPointerException would not have happened had you checked whether the variable was null before using it.

  How about a file that doesn’t exist? Can’t you first check whether the file exists, and then open it? Well, the file might be deleted right after you checked for its existence. Thus, the notion of “existence” depends on the environment, not just on your code.

  The Java Language Specification calls any exception that derives from the class Error or the class RuntimeException an unchecked exception. All other exceptions are called checked exceptions. This is useful terminology that we also adopt. The compiler checks that you provide exception handlers for all checked exceptions.

你可能感兴趣的:(java中的异常)