Download presentation
Presentation is loading. Please wait.
Published byGinger Bishop Modified over 8 years ago
1
Copyright © 1999-2012 Curt Hill Error Handling in Java Throwing and catching exceptions
2
Copyright © 1999-2012 Curt Hill Exceptions Exception: An unexpected problem that prevents normal continuation of the algorithm Examples: divide by zero using a null handle Uncaught exceptions are generally run-time errors
3
Copyright © 1999-2012 Curt Hill Traditional Exception Handling In many languages there is no error handling If we think there is a good chance that a divisor could be zero, we could test it: if(k==0) { // handle error … else j = m/k;
4
Copyright © 1999-2012 Curt Hill Problems There are just too many possible ways to generate an exception If we tested each one with an if most of the code would be error testing
5
Copyright © 1999-2012 Curt Hill Java Exception Handling Java exception handling is having one error handling routine that intercepts all divide by zero exceptions The exception handler can be a long ways from the exception
6
Copyright © 1999-2012 Curt Hill Two Parts of Exception Handling Finding the error and announcing it as an error –Throwing an exception –This uses the throw and throws keyword Handling the exception –Recovery or error handling –This uses the try, catch, and finally keyword
7
Copyright © 1999-2012 Curt Hill Exceptions Everything in Java is a class –Exception is no exception There are at least 35 subclasses of Exception including –ClassNotFoundException –GeneralSecurityException (21 subclasses) –IOException (21 subclasses) –RuntimeException (29 subclasses) Many of these are subclassed as well
8
Copyright © 1999-2012 Curt Hill Exceptions Exception SQLException IOException SecurityException NullPointerException RunTimeException ArithmeticException IndexOutOfBoundsException FileNotFoundException EOFException AWTException ZipException
9
Copyright © 1999-2012 Curt Hill Catching the exception Uses the try catch block try introduces a compound statement This is followed by one or more catch clauses There can also be one finally clause Each catch clause is like a one parameter method that handles that kind of exception
10
Copyright © 1999-2012 Curt Hill try catch syntax Form is: try { // code... } catch (ExceptionType_1 e) { handle exception 1} catch (ExceptionType_2 e) { handle exception 2 }... finally { always executed }
11
Copyright © 1999-2012 Curt Hill Form of catch catch (type parm){stmts} Parameter is an exception type Derived from Exception Only usable in the compound statement Compound statement is like a method body and the Exception (or subclass) is the only parameter
12
Copyright © 1999-2012 Curt Hill Example try catch Catch divide by zero: try { fun(x); } catch(ArithmeticException a){ System.out.println(“Oops”); } catch(Exception e){ System.out.println(“Oops2”); } The error can be in the try or in any function called from within the try
13
Copyright © 1999-2012 Curt Hill Exceptions and the throw Many exceptions are thrown automatically by the Java Virtual Machine These require no intervention on our part We can also throw them manually
14
Copyright © 1999-2012 Curt Hill Throwing an Exception Use new to allocate the exception Use the throw keyword to launch it Example: if(j==0) throw new ArithmeticException(“j was zero”);
15
Copyright © 1999-2012 Curt Hill Exception Constructors Exception and its subclasses usually have two constructors A default A constructor that takes a message This message can be extracted in the catch
16
Copyright © 1999-2012 Curt Hill Exception Methods Exception and its subclasses have several methods of importance getMessage() –Returns the constructor message printStackTrace –No parameters: display on error file –One parameter: file to display on
17
Copyright © 1999-2012 Curt Hill A Better try catch try {... } catch(ArithmeticException a){ System.out.println( a.getMessage()); printStackTrace(System.out); }
18
Copyright © 1999-2012 Curt Hill Cause and Effect The throw and catch do not have to be near each other The throw is like a super return The current function is exited as well as any between this one and the function containing the try and catch Consider in next screen, a main function with a try catch that calls Fun_1, which calls Fun_2, which calls Oops, which throws an exception
19
Copyright © 1999-2012 Curt Hill Call example try{ Fun_1(…) catch(…) throw Oops(...); Fun_2(…) main Fun_1 Fun_2 Oops
20
Copyright © 1999-2012 Curt Hill Exception Processing The call stack between throw and catch is flushed The function and all those in between are terminated They may be re-executed later, but they can not be resumed
21
Copyright © 1999-2012 Curt Hill Nested Trys We do not usually nest a try within another However, to get to our exception we may go through several try catch pairs in several methods The exception is always caught by the closest try Closest in terms of most recently called function
22
Copyright © 1999-2012 Curt Hill Second call example try{ Fun_1(…) catch(…){…} throw Oops(...); try { Fun_2(…); catch(…){…} main Fun_1 Fun_2 Oops
23
Copyright © 1999-2012 Curt Hill Throwing Revisited The throw keyword launches an exception Any function that contains any of these must either handle the exception or announce that it is a possibility The announcement is done with the throws clause
24
Copyright © 1999-2012 Curt Hill The throws clause The throws clause mentions the exception thrown Follows the function parameter list Precedes the opening brace int f(...) throws Exception {... throw new Exception(“Oops”); Announces the possibility of this error, even though it might or might not actually occur
25
Copyright © 1999-2012 Curt Hill More on throws If a function calls a function with a throws clause it must catch what is thrown or have a throws itself There always has to be a catch Throws is not needed for automatics thrown by JVM –Functions that throw a RunTimeException or its subclasses do not need a throws –This is only exception of JVM
26
Methods with Throws Many methods have throws –Particularly in regard to I/O A call of these methods must be within a try catch –Otherwise a syntax error is given Fortunately, that syntax error tells the programmer exactly what exception is to be thrown Copyright © 1999-2012 Curt Hill
27
Multiple Catches A try catch statement can have many catch clauses They are tried in order from top to bottom What the clause handles is based on the parameter to the catch Put the specifics first and the generals later See the subclasses of Exception for more details
28
Copyright © 1999-2012 Curt Hill Order Consider the following: try {…} catch(Exception e){…} catch(IOException i){…} The second catch can never be executed IOException is a subclass of Exception Since checking starts from top, there is no condition that could trigger the second that would not be caught by the first Java compiler flags as an error
29
Copyright © 1999-2012 Curt Hill Finally Clause is always executed, whether exception occurs or not Provides for final cleanup –File closing or cleanup –Network connection termination It is optional Often the catches set a variable that the finally checks to see what cleanup is needed
30
Copyright © 1999-2012 Curt Hill Multiple trys and catches There can be as many try catch statements as wanted The smaller the area protected, the more specific the exception handling can be The larger the area the more general the exception handling
31
Copyright © 1999-2012 Curt Hill Throw and Throw Again A catch may end up with an exception that it does not know how to handle It merely issues a throw and lets someone else handle it It better be nested in an if so that all exceptions are not thrown
32
Copyright © 1999-2012 Curt Hill User Defined Exceptions Like most classes Exception may be subclassed Its subclasses may be also A new Exception class may be defined by subclassing any of these and providing both constructors
33
Copyright © 1999-2012 Curt Hill Throwable Exception is a subclass of Throwable Throwable defines most of the methods: –getMessage –printStackTrace Throwable has another subclass Error –Used for problems that most programs will not catch, such as VirtualMachineError
34
Copyright © 1999-2012 Curt Hill Last Thoughts How do you figure out what exceptions to catch? The documentation always specifies any thrown exceptions There is also the trial and error method –Make the last catch for Exception –Exceptions have a toString method –Display this and it will tell you what you should be catching
35
Copyright © 1999-2012 Curt Hill New Things Keywords –try –catch –throw –throws –finally Classes –Exception and descendents
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.