Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.

Similar presentations


Presentation on theme: "Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because."— Presentation transcript:

1 Exception Handling

2 You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. Logic errors occur when a program doesn't perform the way it was intended to. 6/22/20162

3 3 Exception Handling-Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java exception is an object that describes an exceptional condition that has occurred in a piece of code When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error An exception can be caught to handle it or pass it on Exceptions can be generated by the Java run-time system, or they can be manually generated by your code

4 6/22/20164 Exception Handling Performing action in response to exception Examples Exit program (abort) Deal with exception and continue Print error message Request new data Retry action

5 6/22/20165 Representing Exceptions

6 6/22/20166 Object Error Throwable Exception LinkageError VirtualMachoneError ClassNotFoundException CloneNotSupportedException IOException AWTError … AWTException RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked Checked NoSuchElementException … Representing Exceptions Java Exception class hierarchy

7 System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. 6/22/20167

8 Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. 6/22/20168

9 Checked / Unchecked RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. 6/22/20169

10 In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. 6/22/201610

11 These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions. 6/22/201611

12 6/22/201612 Exception Handling in Java Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally Program statements to monitor are contained within a try block If an exception occurs within the try block, it is thrown Code within catch block catch the exception and handle it

13 try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; }... catch (ExceptionN exVar3) { handler for exceptionN; } 6/22/201613

14 6/22/201614 Example Output: Division by zero. After catch statement.

15 6/22/201615 try and catch statement The scope of a catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement. The statements that are protected by the try must be surrounded by curly braces.

16 6/22/201616 Multiple Catch Clauses If more than one can occur, then we use multiple catch clauses When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed After one catch statement executes, the others are bypassed

17 6/22/201617 Example

18 6/22/201618 Caution Exception subclass must come before any of of their superclasses A catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. So, the subclass would never be reached if it come after its superclass For example, ArithmeticException is a subclass of Exception Moreover, unreachable code in Java generates error

19 6/22/201619 Example

20 6/22/201620 Nested try Statements A try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stack If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match If a method call within a try block has try block within it, then then it is still nested try

21 6/22/201621 Example

22 6/22/201622 throw It is possible for your program to to throw an exception explicitly throw ThrowableInstance Here, ThrowableInstance must be an object of type Throwable or a subclass Throwable There are two ways to obtain a Throwable objects: Using a parameter into a catch clause Creating one with the new operator

23 6/22/201623 Example -throw Statements Output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo

24 6/22/201624 throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list) throws exception-list { // body of method } It is not applicable for Error or RuntimeException, or any of their subclasses

25 6/22/201625 Example: incorrect program

26 6/22/201626 Example: corrected version Output: Inside throwOne. Caught java.lang.IllegalAccessException: demo

27 6/22/201627 Finally Statement finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. finally block will be executed whether or not an exception is thrown. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. Each try clause requires at least one catch or finally clause.

28 28 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements 6/22/2016

29 29 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed 6/22/2016

30 30 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed 6/22/2016

31 31 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2 6/22/2016

32 32 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled. 6/22/2016

33 33 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed. 6/22/2016

34 34 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method is now executed. 6/22/2016

35 35 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; statement2 throws an exception of type Exception2. 6/22/2016

36 36 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handling exception 6/22/2016

37 37 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Execute the final block 6/22/2016

38 38 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Rethrow the exception and control is transferred to the caller 6/22/2016

39 39 Example

40 6/22/201640 Output inside procA procA's finally Exception caught inside procB procB's finally inside procC procC's finally

41 6/22/201641 Uncaught Exceptions class exc0{ public static void main(String args[]) { int d=0; int a=42/d; } A new exception object is constructed and then thrown. This exception is caught by the default handler provided by the java runtime system. The default handler displays a string describing the exception, prints the stack trace from the point at which the exception occurred and terminates the program. Output: java.lang.ArithmeticException: / by zero at exc0.main(exc0.java:4)

42 42 When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); } 6/22/2016

43 43 When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); 6/22/2016

44 44 When to Throw Exceptions An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it. 6/22/2016

45 45 Displaying a Description of an Exception Throwable overrides the toString() method (defined by Object) so that it returns a string containing a description of the exception. Example: catch(ArithmeticException e) { System.out.println(“Exception: “+e); } Output: Exception: java.lang.ArithmeticException: / by zero

46 6/22/201646 User Defined Exception Define a subclass of the Exception class. The new subclass inherits all the methods of Exception and can override them. class MyException extends Exception{ private int a; MyException(int i) { a = i;} public String toString (){ return “MyException[“ + a+”]”;} }

47 6/22/201647 Continuation of the Example class test{ static void compute (int a) throws Myexception{ if(a>10) throw new MyException(a); System.out.println(“Normal Exit”); } public static void main(String args[]){ try{ compute(1); compute(20); }catch(MyException e){ System.out.println(“Caught “ +e); }

48 6/22/201648 Example-2 class InvalidRadiusException extends Exception { private double r; public InvalidRadiusException(double radius){ r = radius; } public void printError(){ System.out.println("Radius [" + r + "] is not valid"); }

49 6/22/201649 Continuation of Example-2 class Circle { double x, y, r; public Circle (double centreX, double centreY, double radius ) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } else { x = centreX ; y = centreY; r = radius; }

50 6/22/201650 Continuation of Example-2 class CircleTest { public static void main(String[] args){ try{ Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); } catch(InvalidRadiusException e) { e.printError(); }


Download ppt "Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because."

Similar presentations


Ads by Google