Thursday, October 22, 2009

Section 7.2. Checked/Unchecked Exceptions and Errors







7.2. Checked/Unchecked Exceptions and Errors

Exceptions and errors fall into three categories: checked exceptions, unchecked exceptions, and errors.

7.2.1. Checked Exceptions

  • Checked exceptions are checked by the compiler at compile time.

  • Methods that throw a checked exception must indicate so in the method declaration using the throws clause. This must continue all the way up the calling stack until the exception is handled.

  • All checked exceptions must be explicitly caught with a catch block.

  • Checked exceptions include exceptions of the type Exception, and all classes that are subtypes of Exception, except for RuntimeException and the subtypes of RuntimeException.

The following is an example of a method that throws a checked exception:

	// Method declaration that throws
// an IOException
void readFile(String filename)
throws IOException {
...
}


7.2.2. Unchecked Exceptions

  • The compiler does not check unchecked exceptions at compile time.

  • Unchecked exceptions occur during runtime due to programmer error (out-of-bounds index, divide by zero, and null pointer exception) or system resource exhaustion.

  • Unchecked exceptions do not have to be caught.

  • Methods that may throw an unchecked exception do not have to (but can) indicate this in the method declaration.

  • Unchecked exceptions include exceptions of the type RuntimeException and all subtypes of RuntimeException.

7.2.3. Errors

  • Errors are typically unrecoverable and present serious conditions.

  • Errors are not checked at compile time and do not have to be (but can be) caught/handled.

Any checked exceptions, unchecked exceptions, or errors can be caught.









No comments:

Post a Comment