Robustness Exception Handling Robust Programs A robust program
![Robustness & Exception Handling Robustness & Exception Handling](https://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-1.jpg)
Robustness & Exception Handling
![Robust Programs A robust program deals gracefully with unexpected input (among other things). How Robust Programs A robust program deals gracefully with unexpected input (among other things). How](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-2.jpg)
Robust Programs A robust program deals gracefully with unexpected input (among other things). How can we make this more robust? More specifically, what happens if the user doesn't enter an integer, [while program is waiting for that], instead the user press any character input? Or, if someone access an array beyond the allocation of array.
![Exceptions An exception is an abnormal condition that arises in a piece of code Exceptions An exception is an abnormal condition that arises in a piece of code](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-3.jpg)
Exceptions An exception is an abnormal condition that arises in a piece of code at run time n An exception is a run-time error If these exceptions are not prevented or at least handled properly, n n either the program will be aborted abnormally, or the incorrect result will be carried on.
![Exception Handling Mechanism When an exception condition arises, n n n an object of Exception Handling Mechanism When an exception condition arises, n n n an object of](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-4.jpg)
Exception Handling Mechanism When an exception condition arises, n n n an object of the respective exception class is created and thrown in the method that caused the exception. That method may choose to handle the exception itself or pass it on. Either way, at some point, the exception is caught and processed Exceptions can be generated by Java run-time system or can be manually generated by your code n Java exception handling is managed via five keywords: try, catch, throws, finally
![Exception Handling Mechanism Program statements that you want to monitor for exceptions are contained Exception Handling Mechanism Program statements that you want to monitor for exceptions are contained](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-5.jpg)
Exception Handling Mechanism Program statements that you want to monitor for exceptions are contained within a try block. n If exception occurs within try block, it is thrown. Your code can catch this exception using catch and handle it. System generated exceptions are automatically thrown by Java run-time system n To manually throw an exception, use the keyword throw
![Exception Handling Mechanism If a method is capable of causing an exception that it Exception Handling Mechanism If a method is capable of causing an exception that it](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-6.jpg)
Exception Handling Mechanism If a method is capable of causing an exception that it does not handle, n n it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration Any code that must be executed before a method returns is put in a finally block
![java. lang. Throwable java. lang. Error java. lang. Exception java. lang. Runtime. Exception java. java. lang. Throwable java. lang. Error java. lang. Exception java. lang. Runtime. Exception java.](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-7.jpg)
java. lang. Throwable java. lang. Error java. lang. Exception java. lang. Runtime. Exception java. lang. Array. Index. Out. Of. Bounds. Exception
![Hierarchy of Exceptions The class Exception is used for exceptional conditions that user programs Hierarchy of Exceptions The class Exception is used for exceptional conditions that user programs](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-8.jpg)
Hierarchy of Exceptions The class Exception is used for exceptional conditions that user programs can catch The class Error - defines the conditions that should not be expected to be caught under normal circumstances. - responsible for giving errors in some catastrophic failures that can’t usually be handled by your program. The class Runtime. Exception is used for exceptions n that are automatically defined for the programs during run time in response to some execution error.
![Exceptions Some examples of exceptions are: n n n Index. Out. Of. Bounds. Exception Exceptions Some examples of exceptions are: n n n Index. Out. Of. Bounds. Exception](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-9.jpg)
Exceptions Some examples of exceptions are: n n n Index. Out. Of. Bounds. Exception Null. Pointer. Exception Number. Format. Exception Arithmetic. Exception File. IOException
![Java’s Built-in Exceptions Some Runtime Exception Subclasses Arithmetic. Exception Array. Index. Outof. Bound. Exception Java’s Built-in Exceptions Some Runtime Exception Subclasses Arithmetic. Exception Array. Index. Outof. Bound. Exception](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-10.jpg)
Java’s Built-in Exceptions Some Runtime Exception Subclasses Arithmetic. Exception Array. Index. Outof. Bound. Exception Class. Cast. Exception Null. Pointer. Exception Number. Format. Exception Some Exception Subclasses Class. Not. Found. Exception No. Such. Method. Exception Illegal. Access. Exception
![Errors Some Error Subclasses Outof. Memory. Error Virtual. Machine. Error Stack. Overflow. Error Errors Some Error Subclasses Outof. Memory. Error Virtual. Machine. Error Stack. Overflow. Error](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-11.jpg)
Errors Some Error Subclasses Outof. Memory. Error Virtual. Machine. Error Stack. Overflow. Error
![try { // some code that might throw an exception } catch (Exception. Type try { // some code that might throw an exception } catch (Exception. Type](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-12.jpg)
try { // some code that might throw an exception } catch (Exception. Type 1 excep. Obj) { // exception handler for Exception. Type 1 } catch (Exception. Type 2 excep. Obj) { // exception handler for Exception. Type 2 } //… finally { // code to be executed before try block ends } Here, Exception. Type 1 and Exception. Type 2 is the type of exception that has occured
![Uncaught Exceptions class Exc 0 { public static void main(String args[]) { int d Uncaught Exceptions class Exc 0 { public static void main(String args[]) { int d](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-13.jpg)
Uncaught Exceptions class Exc 0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } Java. lang. Arithmatic. Exception: / by zero at Exc 0. main(Exc 0. java: 4)
![Uncaught Exceptions class Exc 1 { static void subroutine() { int d = 0; Uncaught Exceptions class Exc 1 { static void subroutine() { int d = 0;](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-14.jpg)
Uncaught Exceptions class Exc 1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc 1. subroutine(); } } Java. lang. Arithmatic. Exception: / by zero at Exc 1. subroutine (Exc 1. java: 4) at Exc 1. main(Exc 1. java: 7)
![‘try’ and ‘catch’ class Exc 2 { public static void main(String args[]) { int ‘try’ and ‘catch’ class Exc 2 { public static void main(String args[]) { int](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-15.jpg)
‘try’ and ‘catch’ class Exc 2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System. out. println("This will not be printed. "); } catch (Arithmetic. Exception e) { // catch divide-by-zero error System. out. println("Division by zero. "); } System. out. println("After catch statement. "); } } Division by zero After catch statement
![Multiple catch Clauses class Multi. Catch{ public static void main(String args[]){ try { int Multiple catch Clauses class Multi. Catch{ public static void main(String args[]){ try { int](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-16.jpg)
Multiple catch Clauses class Multi. Catch{ public static void main(String args[]){ try { int a = args. legth; System. out. println(“a = “+a); int b = 42/a; int c[] = {1}; c[2] = 99; } catch (Arithmetic. Exception e) { System. out. println(“Divide by 0: “+e); } catch (Array. Index. Out. Of. Bounds. Exception e) { System. out. println(“Array index oob: “+e); } finally { System. out. println(“I am in finally block!”); } }
![Multi. Catch java Multi. Catch a = 0 Divide by 0: java. lang. Arithmetic. Multi. Catch java Multi. Catch a = 0 Divide by 0: java. lang. Arithmetic.](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-17.jpg)
Multi. Catch java Multi. Catch a = 0 Divide by 0: java. lang. Arithmetic. Exception: / by zero I am in finally block! java Multi. Catch Test. Arg a = 1 Array index oob: java. lang. Array. Index. Out. Of. Bounds. Exception I am in finally block!
![Multiple catch Clauses (restriction) /* This program contains an error. A subclass must come Multiple catch Clauses (restriction) /* This program contains an error. A subclass must come](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-18.jpg)
Multiple catch Clauses (restriction) /* This program contains an error. A subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result. */ class Super. Sub. Catch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System. out. println("Generic Exception catch. "); } /* This catch is never reached because Arithmetic. Exception is a subclass of Exception. */ catch(Arithmetic. Exception e) { // ERROR - unreachable System. out. println("This is never reached. "); } } }
![// An example nested try statements. class Nest. Try { public static void main(String // An example nested try statements. class Nest. Try { public static void main(String](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-19.jpg)
// An example nested try statements. class Nest. Try { public static void main(String args[]) { try { int a = args. length; /* If no command line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System. out. println("a = " + a); try { // nested try block /* If one command line arg is used, then an divide-by-zero exception will be generated in following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command line args are used then generate an out-of-bounds exception. */ if(a==2) { int c[ ] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch (Array. Index. Out. Of. Bounds. Exception e) { System. out. println("Array index out-of-bounds: " + e); } } catch (Arithmetic. Exception e) { System. out. println("Divide by 0: " + e); } } } C: java Nest. Try Divide by 0: java. lang. Arithmatic. Exception: / by zero C: java Nest. Try One a=1 Divide by 0: java. lang. Arithmatic. Exception: / by zero C: java Nest. Try One Two a=2 Array index out-of-bounds: java. lang. Array. Index. Out. Of. Bounds. Exception: 42
![throw General form of throw: throw thr. Obj; Where ‘thr. Obj’ must be an throw General form of throw: throw thr. Obj; Where ‘thr. Obj’ must be an](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-20.jpg)
throw General form of throw: throw thr. Obj; Where ‘thr. Obj’ must be an object of type Throwable or a subclass of Throwable n Simple types, such as int or char, as well as non. Throwable classes, [such as String and Object], cannot be used as exceptions. The flow of execution stops immediately after the throw statement; n any subsequent statements are not executed
![class Throw. Demo{ static void demoproc(){ try { throw new Null. Pointer. Exception(“demo”); } class Throw. Demo{ static void demoproc(){ try { throw new Null. Pointer. Exception(“demo”); }](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-21.jpg)
class Throw. Demo{ static void demoproc(){ try { throw new Null. Pointer. Exception(“demo”); } catch (Null. Pointer. Exception e) { System. out. println(“Caught in demoproc”); throw e; } } public static void main(String args[]){ try { demoproc(); } catch (Null. Pointer. Exception e) { System. out. println(“Recaught: “+e); } Caught in demoproc }} Recaught: java. lang. Null. Pointer. Exception: demo
![throw Here is the output Caught in demoproc Recaught: java. lang. Null. Pointer. Exception: throw Here is the output Caught in demoproc Recaught: java. lang. Null. Pointer. Exception:](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-22.jpg)
throw Here is the output Caught in demoproc Recaught: java. lang. Null. Pointer. Exception: demo All of Java’s built-in run-time exceptions have two constructors: n n n one with no parameter one takes a string parameter When the second form is used, the argument specifies a string that describes the exception w This string is displayed when the object is used as an argument to print() or println()
![Throwing Exceptions Some exceptions are thrown "automatically" by the Java Virtual Machine. e. g. Throwing Exceptions Some exceptions are thrown "automatically" by the Java Virtual Machine. e. g.](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-23.jpg)
Throwing Exceptions Some exceptions are thrown "automatically" by the Java Virtual Machine. e. g. Index. Out. Of. Bounds. Exception You can also throw some exceptions yourself.
![The throws clause When do you need a throws? There are two types of The throws clause When do you need a throws? There are two types of](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-24.jpg)
The throws clause When do you need a throws? There are two types of exceptions in Java n n checked exceptions, and unchecked exceptions. Checked exceptions require a throws clause whenever they might be thrown. Unchecked exceptions are things like Null. Pointer. Exception, and Index. Out. Of. Bounds. Exception. needs no throws clause.
![Checked vs Unchecked exceptions are exceptions that are instances of – java. lang. Runtime. Checked vs Unchecked exceptions are exceptions that are instances of – java. lang. Runtime.](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-25.jpg)
Checked vs Unchecked exceptions are exceptions that are instances of – java. lang. Runtime. Exception, java. lang. Error, or one of their subclasses. n They are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. Everything else is a checked exception.
![java. lang. Throwable checked unchecked java. lang. Error java. lang. Exception java. lang. Runtime. java. lang. Throwable checked unchecked java. lang. Error java. lang. Exception java. lang. Runtime.](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-26.jpg)
java. lang. Throwable checked unchecked java. lang. Error java. lang. Exception java. lang. Runtime. Exception java. lang. Index. Out. Of. Bounds. Exception
![The throws clause A throws clause lists the types of exceptions that a method The throws clause A throws clause lists the types of exceptions that a method](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-27.jpg)
The throws clause A throws clause lists the types of exceptions that a method might throw n This is necessary for all exceptions, except those of type Error or Runtime. Exception, or any of their subclasses All other exceptions that a method can throw must be declared in the throws clause. n Otherwise, a compile time error will result General form type method. Name(param. List) throws exception. List { // body of method}
![// This program contains an error and will not compile. class Throws. Demo { // This program contains an error and will not compile. class Throws. Demo {](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-28.jpg)
// This program contains an error and will not compile. class Throws. Demo { static void throw. One() { System. out. println("Inside throw. One. "); throw new Illegal. Access. Exception("demo"); } public static void main(String args[]) { throw. One(); } }
![class Throws. Demo{ static void throw. One() throws Illegal. Access. Exception{ System. out. println(“In class Throws. Demo{ static void throw. One() throws Illegal. Access. Exception{ System. out. println(“In](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-29.jpg)
class Throws. Demo{ static void throw. One() throws Illegal. Access. Exception{ System. out. println(“In throw. One”); throw new Illegal. Access. Exception(“demo”); } public static void main(String args[]){ try { throw. One(); } catch (Illegal. Access. Exception e) { System. out. println(“Caught: “+e); } } } In throw. One Caught: java. lang. Illegal. Access. Exception: demo
![Finally The finally clause can be useful for closing file handles and freeing up Finally The finally clause can be useful for closing file handles and freeing up](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-30.jpg)
Finally The finally clause can be useful for closing file handles and freeing up any other resources n that might have been allocated at the beginning of a method with the intent of disposing of them before returning finally creates a block of code that will be executed after try/catch has completed. n It will executed whether or not an exception is thrown. The finally clause is optional Each try statement requires at least one catch or a finally clause
![// Demonstrate finally. // Execute a try block normally. class Finally. Demo { static // Demonstrate finally. // Execute a try block normally. class Finally. Demo { static](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-31.jpg)
// Demonstrate finally. // Execute a try block normally. class Finally. Demo { static void proc. C() { // Through an exception out of the method. try { static void proc. A() { System. out. println("inside proc. C"); try { } finally { System. out. println("inside proc. A"); System. out. println("proc. C's finally"); throw new Runtime. Exception("demo"); } } finally { } System. out. println("proc. A's finally"); public static void main(String args[]) { } try { } proc. A(); // Return from within a try block. } catch (Exception e) { static void proc. B() { System. out. println("Exception caught"); try { } System. out. println("inside proc. B"); proc. B(); return; proc. C(); } finally { System. out. println("proc. B's finally"); } } inside proc. A’s finally Exception caught inside proc. B’s finally inside proc. C’s finally
![Creating Own Exception // This program creates a custom exception type. class My. Exception Creating Own Exception // This program creates a custom exception type. class My. Exception](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-32.jpg)
Creating Own Exception // This program creates a custom exception type. class My. Exception extends Exception { private int detail; My. Exception(int a) { detail = a; } } public String to. String() { return "My. Exception[" + detail + "]"; }
![Creating Own Exception class Exception. Demo { static void compute(int a) throws My. Exception Creating Own Exception class Exception. Demo { static void compute(int a) throws My. Exception](http://slidetodoc.com/presentation_image_h/83604676b5d7f3b8980868445433e5c8/image-33.jpg)
Creating Own Exception class Exception. Demo { static void compute(int a) throws My. Exception { System. out. println("Called compute (" + a + ")” ) ; if(a > 10) throw new My. Exception(a); System. out. println("Normal exit"); } } public static void main(String args[ ]) { try { compute(1); compute(20); } catch (My. Exception e) { System. out. println("Caught: " + e); } } Called compute (1) Normal exit Called compute (20) Caught: My. Exception [20]
- Slides: 33