Skill-Building Exercises


Summary

Errors and Exceptions are thrown by the Java Virtual Machine to indicate or signal the occurrence of an exceptional (abnormal) condition. The Throwable class is the root of all Errors and Exceptions.

Errors are thrown when a serious condition exists from which recovery is not possible. Errors are not handled by the programmer since they can potentially happen at any time under circumstances beyond their control.

Exceptions must be handled explicitly by the programmer unless the Exception is a RuntimeException. RuntimeExceptions can occur during the normal execution of the Java Virtual Machine. Although RuntimeExceptions can generally be ignored, the prudent programmer should give careful thought to their occurrence and handle them accordingly.

Classes that extend Exception are referred to as checked exceptions. The Java compiler will signal your failure to properly handle a checked exception. RuntimeExceptions and Errors are referred to as unchecked exceptions because programmers are not explicitly required to catch and handle them in their code.

Code that might throw a checked exception must be contained in a try block unless the method in which it appears uses the throws clause to indicate it might throw the exception. Failure to properly handle a checked exception will result in a compiler error. Code that might throw an unchecked exception can optionally be contained in a try block. A try block must be accompanied by either one or more catch blocks, a finally block, or a combination of both.

The Throwable class provides some useful methods for getting information about the nature of an exception. Some exceptions provide additional information about themselves. This is especially true of exceptions belonging to the java.io and java.net packages. Consult the Java Platform API documentation for detailed information about specific exception types.

Use the throws clause in a method declaration to indicate what type(s) of exception(s) a method might throw.

Create custom exceptions by extending the Exception class. Choose the names of your exception abstractions as carefully as you choose other program abstraction names.

You can chain low-level exceptions to higher level exception abstractions by catching the low-level abstraction in a catch block and using it as a cause argument for a custom exception. You can gain access to an exception’s cause via the Throwable.getCause() method.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net