260 likes | 522 Views
Exceptions in the Java programming language. J. W. Rider. Background. Whenever you invoke an object’s method, you have no way of knowing if the “normal” behavior is going to be successfully completed. When building robust programs, you need to accommodate situations outside of the norm.
E N D
Exceptionsin the Java programming language J. W. Rider
Background • Whenever you invoke an object’s method, you have no way of knowing if the “normal” behavior is going to be successfully completed. • When building robust programs, you need to accommodate situations outside of the norm.
Methodic communications Ways a method can communicate with other parts of a program • Return value • Output parameters (object/array) • In-scope variable assignment (“side effect”) • Method invocation • Throw exception
Before exceptions… • Testing of return results or global variables after every statement. • Global functions would be called to handle all possible conditions. Recovery would be determined in one place in the program. This was fine. However, testing every statement obscured the exception-free nominal path to programmers. Global exception handlers precluded local handling of exception conditions.
Java Exceptions • The Throwable class hierarchy • The throw statement • The throws clause • The try statement
Throwable hierarchy For conditions that a reasonable program should catch. Object Throwable Error Exception For serious conditions that a reasonable program should not catch. RuntimeException
Throwable class • Constructed with no argument or with a String error message • Useful instance methods: • getMessage() • printStackTrace() • toString() • Subclasses Error and RuntimeException not required to be listed in throws clause.
Throwable classes • Throwable • Error • Exception • RuntimeException • ArithmeticException,ArrayStoreException • IllegalArgumentException,IndexOutOfBoundsException • NullPointerException • IOException • FileNotFoundException • EndOfFileException
Throw statement • throwThrowable-reference; • throw new MyException(); • Interrupts nominal program flow. No more statements in the current sequence are executed. The exception must be handled in an encompassing try statement, or the program terminates.
Jump statements • Jump statements interrupt structured program flow. • Return • Break • Continue • Throw • Jump statements must be the last in any given sequence of statements. They are frequently part of a conditional statement.
Throws clause • Added to a method header to indicate that an unhandled exception may arise during execution of the method. • … throws Throwable1, Throwable2, ThrowableN • A method that invokes the throwing method must either handle the exception when it arises, or also include a throws clause in its declaration.
Method declaration • Method header • Ordinary member • Constructor • Static block/initializer • Method body • Enclosed in braces • Abbreviated with a semicolon.
Method header • Qualifiers • Return-type • Method-name • Formal arguments • Throws clause Prototype Signature
Try statement • Provides a structured approach to exception handling. • Try block • Catch section • One or more catch blocks • Finally block • The try block is always required. Either a catch section or finally block or both follow.
Structured statements • Sequence • Block (enclosed in braces) • Conditional statements • If statement • Switch statement • Iterative statements • While statement • For statement • Do statement • Try statement “Canonical” structures Structured exception handling
Try block • Identifies the “nominal” flow of control through a try statement. It is a sequence of statements. • If no exception occurs, all the statements in the try block are executed in sequence. • If an exception occurs, the statement being executed is interrupted, and none of the statements following are executed. The whole try block is interrupted.
Try block figure This is our nominal control flow. We establish the try block around those statements where we do NOT want to continue if an exception occurs. try { doFirst(); doSecond(); doThird(); }
Catch section • Immediately follows the try block. • Composed of a series of catch blocks. • Is only entered if an exception occurs in the try block. • Only one of the catch blocks are executed.
Catch block • When a catch block is executed, the exception is “deemed” handled, even if the catch body is empty. catch (MyException e) { … // exception handling code }
Finally block • Envelopes a sequence of statements that must be executed whether the try block is interrupted or not. • Does NOT handle the exception. • Does not have any way to determine whether an exception has occurred, or if it has been handled. • If an exception has not been handled, the exception is still active at the end of the finally block and interrupts the method where the try statement is embedded.
Example scenario • A resource holds items that need to be processed individually. While exceptions may occur at any point during processing, we are only expected to recover from the “EmptyResourceException” that arises when we attempt to extract an item from an empty resource. There is no way to determine if a resource is empty without attempting an extraction. • Regardless of whether an exception occurs or not, if we open a resource for processing, we must close the resource.
Example code Resource rez=Resource.open(resourcename); try { while(true) { Item item=rez.extractItem(); item.process(); } } catch(EmptyResourceException e) {} finally { rez.close(); }
Exceptions Are part of the Java language. Compiler treats Throwable, Error and RuntimeException special. Program terminated if not handled. Events Are implemented as user classes in a library. No special treatment. Events are notifications that something has happened, but do not require handling. Exceptions vs Events
Summary • Exception handling provides a new control flow structure through Java programs. • The try statement provides for • watching a nominal sequence of statements • handling the exceptions we expect • ensuring statements that must be executed, are.