Exceptions Exceptions n n Many problems in code
Exceptions
Exceptions n n Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run q n Must run the program to actually determine the values of variables, get user input, etc. These errors that occur when the program is running are “exceptions”
Exceptions n An exception is an object that describes an unusual or erroneous situation n Exceptions are generated by part of a program, and may be handled by another part of the program n A program can be separated into a normal execution flow and an exception execution flow n An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught 3
Exception Handling n Java has a predefined set of exceptions and errors that can occur during execution n A program can deal with an exception in one of three ways: q q q n ignore it handle it where it occurs handle it an another place in the program The manner in which an exception is processed is an important design consideration 4
Exception Handling n If an exception isn’t handled by the program, it halts and prints an error: Exception in thread “main” java. lang. Null. Pointer. Exception at Some. Class. method(Some. Class. java: 54) at Except. e 2(Except. java: 12) at Except. main(Except. java: 22) n The error message gives the type of exception that was thrown (Null. Pointer. Exception) n and the “stack trace”…
The Call Stack Trace n Indicates the line on which the exception occurred q n (Some. Class. java: 54) Shows the method call trail that lead to the attempted execution of the offending line q main → e 2 → method 6
Tracing Problems n The call stack can be very long, and call methods in many libraries Exception at at n in thread “main” java. util. Unknown. Format. Conversion. Exception : Conversion = ‘i’ java. util. Formatter$Format. Specifier. conversion(Formatter. java: 2603) java. util. Formatter$Format. Specifier. <init>(Formatter. java: 2631) java. util. Formatter. parse(Formatter. java: 2477) java. util. Formatter. format(Formatter. java: 2411) java. io. Print. Stream. format(Print. Stream. java: 899) java. io. Print. Stream. printf(Print. Stream. java: 800) Except. e 3(Except. java: 17) Except. main(Except. java: 22) It can be tricky to find the “real” cause q should be the innermost code that isn’t fully tested
The Exception Class n n In Java, exceptions are objects There is a hierarchy of exception types, with Exception at the top q n you don’t generally instantiate Exception; one is automatically created when there is an error There are many subclasses of Exception that are used for particular types of errors
Exception Subclasses n The subclasses of Exception are types that more specifically identify the problem, e. g. : q Arithmetic. Exception n q Index. Out. Of. Bounds. Exception n q array/List/String index doesn’t exist No. Class. Def. Found. Error n n most often caused by a divide-by-zero . class file was there when compiling, but not there now Tend to have informative names: useful errors
The Exception Class Hierarchy n All error and exception classes are descendents of the Throwable class n A programmer can define an exception by extending the Exception class or one of its descendants n The parent class used depends on how the new exception will be used 10
Catching Exceptions n We say that a certain block of code “throws” an exception q n How do you handle something that is thrown at the interpreter? q n think: when the exception occurs, an exception object is generated and tossed at the interpreter you “catch” it Uncaught exceptions stop the program… caught exceptions do not
The try Statement n To handle an exception in a program, the line that throws the exception is executed within a try block n A try block is followed by one or more catch clauses n Each catch clause has an associated exception type and is called an exception handler n When an exception occurs, processing continues at the first catch clause that matches the exception type 12
A try/catch sequence try { \ execute the code that you find here } catch(Exception e) { \ if there is an exception \ then you do the stuff in this part }
An Example try { int x; x = 10/0; } catch(Exception e) { System. out. println(“error occurred”); }
The Exception Parameter n The catch is a little like an else, and a little like a function definition q q q n try {…} catch(Exception e) {…} The argument (“exception parameter”) is assigned to an appropriate Exception object In the divide-by-zero example, e will be an instance of Arithmetic. Exception The exception parameter’s value can be ignored if you don’t need to use it
Another Example try { int x; x = 10/0; } catch(Arithmetic. Exception e) { System. out. println(“divided by 0”); }
Being Specific n Can have multiple catch blocks n The exception parameter type allows different types of exceptions to be handled differently
Being Specific try { int x = userin. next. Int(); Most likely causes System. out. println(10/x); } catch(Arithmetic. Exception e) { System. out. println(“no zeroes”); } catch(Input. Mismatch. Exception e) { System. out. println(“enter a number”); }
Being Specific n The exception parameter is matched like arguments in an overloaded function q q n The type of exception thrown is matched against the exception parameters That class… or any subclass… will match Examples: q q Exception matches all exceptions Index. Out. Of. Bounds matches both array and string exceptions
The Catch All try { … a bunch of code, involving an integer x… System. out. println(10/x); } catch(Arithmetic. Exception e) { System. out. println(“no zeroes”); } catch(Exception e) { System. out. println(“some other problem”); }
However… n In general, use a type as specific as possible q q only catch the exceptions you want to catch and handle properly Don’t incorrectly handle other problems n n the catch-all hides problems you might want to know about Other exceptions are propogated q they can be caught farther up the call stack
Exception Propagation n An exception can be handled at a higher level if it is not appropriate to handle it where it occurs n Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method n A try block that contains a call to a method in which an exception is thrown can be used to catch that exception 22
Checked versus Unchecked n An exception is either checked or unchecked n An unchecked exception does not require explicit handling, though it could be processed that way n The only unchecked exceptions in Java are objects of type Runtime. Exception or any of its descendants n Errors are similar to Runtime. Exception and its descendants in that: q Errors should not be caught q Errors do not require a throws clause
Checked Exceptions n Checked exceptions (other subclasses of Exception) must be handled explicitly q q n must be caught by a method in a catch block must be listed in the throws clause of any method that might throw it The compiler will issue an error if a checked exception is not caught or asserted in a throws clause 24
The throws Clause n Used to indicate that the method will “handle” the checked exception by passing it off to the calling code q Similarly, the calling code must either catch it or be declared indicating that it throws the exception public int my. Method() throws Exception 1, Exception 2 n Any uncaught checked exceptions must be listed in the throws clause
The throw Statement n When your code gets to a situation it can’t handle, it can throw an exception q n Create an instance of the appropriate exception class q n e. g. constructor/setter given an illegal value new Some. Exception(“Error message”); Throw the exception with a throw statement q throw new Some. Exception(“message”);
The throw Statement n The throw statement appears in the body of a method, with an appropriate throws clause n Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown if(x<0) throw new Negative. Input. Exception; 27
Example n From the Student class: public void set. First. Name(String name) { if(name. length()>0) first. Name = name; else throw new Illegal. Argument. Exception (“Name must have length >0”); }
The finally Clause n A try statement can have an optional clause following the catch clauses, designated by the reserved word finally n The statements in the finally clause always are executed n If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete n If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete 29
Why use finally ? n n To make sure that a certain part of an algorithm are executed To leave objects in a stable state q q e. g. An object representing a database connection might be disconnected when an error occurs … there are good security reasons for doing this
- Slides: 30