Exception is an abnormal condition that arises when executing a program. In the languages that do not support exception handling, errors must be checked and handled manually, usually through the use of error codes. In contrast, Java: 1) provides syntactic mechanisms to signal, detect and handle errors 2) ensures a clean separation between the code executed in the absence of errors and the code to handle various kinds of errors 3) brings run-time error management into object-oriented programming
Exception Handling
An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: 1) when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it 2) that method may choose to handle the exception itself or pass it on 3) either way, at some point, the exception is caught and processed
Exception Sources
Exceptions can be: 1) generated by the Java run-time system Fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. 2) manually generated by programmer’s code Such exceptions are typically used to report some error conditions to the caller of a method.
Exception Constructs
Five constructs are used in exception handling: 1) try – a block surrounding program statements to monitor for exceptions 2) catch – together with try, catches specific kinds of exceptions and handles them in some way 3) finally – specifies any code that absolutely must be executed whether or not an exception occurs 4) throw – used to throw a specific exception from the program 5) throws – specifies which exceptions a given method can throw
Exception-Handling Block
General form: try { … } catch(Exception1 ex1) { … } catch(Exception2 ex2) { … } … finally { … } where: 1) try { … } is the block of code to monitor for exceptions 2) catch(Exception ex) { … } is