Subsections
- Applications can run into many kinds of errors during execution.
- Java exceptions provide a clean way to check for errors without cluttering code, and provide a mechanism to signal errors directly.
- Exceptions are also part of a method's contract.
- An exception is thrown when an unexpected error condition is encountered.
- The exception is then caught be an encompassing clause further up the method invocation stack.
Upon completion of this section, students will be able to:
- Create their own Exception class.
- Throw an exception.
- Define the three choices you have when a method throws an exception.
- Use try/catch/finally to run a method that may throw an exception.
- Describe the purpose of the finally clause, and when it is run.
- Make better decisions about when to throw exceptions in your code.
- Exceptions are thrown using the throw statement.
- Exceptions are objects, so they must be created (with new) before being thrown.
- The exceptions a method can throw are declared with a throws clause.
- The exceptions a method can throw are as important as the value type the method returns.
- Catch the exception and handle it.
- Catch the exception and map it to one of your exceptions by throwing an exception of a type declared in your own throws clause.
- Declare the exception in your throws clause and let the exception pass through your method.
- Exceptions are caught by enclosing code in try blocks.
- The body of try is executed until an exception is thrown or it finishes successfully.
- If an exception is thrown, each catch clause is examined in turn, from first to last, to see whether the exception object is assignable tto the type declared with the catch.
- When an assignable catch is found, its code block is executed. No other catch clause will be executed.
- Any number of catch clauses can be associated with a try, as long as each clause catches a different type of exception.
- If a finally clause is present in the try block, the code is executed after all other processing in the try is complete. This happens no matterhow the try clause completed - normally, through an exception, or through a return or break.
- A mechanism for executing a section of code whether or not an exception is thrown.
- Usually used to clean up internal state or to release non-object resources, such as open files stored in local variables.
- Can also be used to cleanup for break, continue, and return.
- No way to leave a try block without executing its finally clause.
- A finally clause is always entered with a reason; that reason is remembered when the finally clause exits.
- Used for "unexpected error conditions".
- Not meant for simple expected situations (end of an input stream should be expected).
|
|