Day 5 Exception Handling

Views:
 
Category: Entertainment
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Exception Handling :

Exception Handling

Objectives:

Objectives At the end of this session, you will be able to Deal with Exceptions Differentiate checked and unchecked exceptions Catch & throw exceptions Use try, catch, finally, throw and throws keywords Handle predefined exceptions Create User defined exceptions Copyright © 2016 Tech Mahindra. All Rights Reserved.

Agenda:

Agenda Introduction to Exceptions Checked & Unchecked Exceptions Using try, catch, finally, throw, throws Predefined exceptions User defined exceptions Copyright © 2016 Tech Mahindra. All Rights Reserved.

Errors:

Errors An error is an unforeseen situation that occurs during program execution which makes further execution impossible. The question is: What to do when an error occurs? How is the error handled? Who handles the error? Can the program recover from that error? Java uses exceptions to provide the error-handling capabilities. Copyright © 2016 Tech Mahindra. All Rights Reserved.

Exceptions:

Exceptions An exception is an event , which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs , the exception is thrown . If the method does not handle the exception, it is thrown to its caller function Eventually if an exception is thrown out of main function, the program is terminated abnormally JVM halts and the stack trace will be printed to the output Copyright © 2016 Tech Mahindra. All Rights Reserved.

Exception:

Exception Uncaught Exception: 1. class ExceptionDemo { 2. public static void main (String args[]) { 3. int d = 0 ; 4. int a = 27/d ; //Divide by Zero 5. System.out.println("Will I be printed?"); 6. } 7. } Output: throws Exception:java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:4) Copyright © 2016 Tech Mahindra. All Rights Reserved.

Exceptions:

Exceptions Exceptions are of two types: Compiler-enforced exceptions, or Checked Exceptions Runtime Exceptions, or Unchecked Exceptions Not caused by program errors. Not required to handle eg . Out of memory Throwable Error Exception RuntimeException SQLException IOException ArithmeticException FileNotFoundException Copyright © 2016 Tech Mahindra. All Rights Reserved.

Categories of Exceptions:

Categories of Exceptions Unchecked Not checked by the compiler at compile time Does not force the client program / method to declare each exception thrown by a method, or even handle it All exceptions are derived from RuntimeException class Checked Checked by the compiler to see if these exceptions are properly caught or specified, & if not, the code fails to compile Forces client program to deal with the scenario in which an exception may be thrown All exceptions which are not derived from RuntimeException class Copyright © 2016 Tech Mahindra. All Rights Reserved.

Exception Handling:

Exception Handling An exception handler consists of two core blocks: The try block encloses some code which might throw an exception (i.e. generate an error). The catch block contains the error handling code, i.e. determines what should be done if an error is detected. Copyright © 2016 Tech Mahindra. All Rights Reserved.

try-catch block:

try-catch block Any code that could result in an exception should be placed in a try block . The catch block contains the code that will execute only when an exception is thrown. If an exception is thrown in the try block, execution control jumps to the catch block that can handle the exception. The exception object is forwarded as an argument to the catch block where the Exception is caught After executing the catch block, the normal flow of program resumes Copyright © 2016 Tech Mahindra. All Rights Reserved.

try-catch Block:

try-catch Block class ExceptionDemo { public static void main (String args []) { int d, a ; try{ d = 0 ; a = 27 / d; System.out.println ("This will not be printed"); }catch ( ArithmeticException e) { System.out.println (“You can not divide an integer by zero"); } System.out.println ("After catch block."); } Output : You can not divide an integer by zero. After catch block. Copyright © 2016 Tech Mahindra. All Rights Reserved.

Multiple catch Blocks:

Multiple catch Blocks A try block can have multiple catch blocks. However, they should handle the exceptions as per the exception hierarchy , Catch blocks to handle subclass exceptions must precede the catch blocks for super class exceptions Generally, the last catch block is the generic Exception class to handle exceptions not caught in the previous catch blocks for specific exceptions Copyright © 2016 Tech Mahindra. All Rights Reserved.

Multiple catch Blocks:

Multiple catch Blocks public class FileReaderCode { public static void main (String[] args ){ try{ String fName = args [0]; //Filename as command line argument //code to read File Contents } catch ( ArrayIndexOutOfBoundsException aio ){ //Handle the exception when user doesn’t enter filename } catch ( java.io. FileNotFoundException fnf ){ //Handle the exception when file does not exist } catch ( Exception e){ //Handle all other exceptions } } } // To run use: java FileReaderCode fileName Copyright © 2016 Tech Mahindra. All Rights Reserved.

finally Block:

finally Block The finally block executes irrespective of an exception being thrown or not. Thus, it is ideally used for closing the resources such as file handlers or database connections acquired during the execution of the method. The only situation when finally will not be executed is when the JVM shuts down. try { // some code that throws an exception } catch (Exception e) { // handle the exception, display a message, whatever } finally { //perform cleanup operations } A try block must be accompanied by at least one catch block or one finally block Copyright © 2016 Tech Mahindra. All Rights Reserved.

throws Clause:

throws Clause If a method is capable of causing an exception that it does not handle, it must specify this behavior u sing throws clause The responsibility of dealing with the exception is forwarded to the caller of the method The throws clause lists the types of exceptions that a method might throw. void myMethod() throws <ExceptionType1>,<ExceptionType2> { //Code that might throw a checked exception } Unchecked Exceptions, i.e. Error or RuntimeException, or any of their subclasses need not be specified. Copyright © 2016 Tech Mahindra. All Rights Reserved.

throw Statement:

throw Statement A program can explicitly throw an exception using the throw statement. throw someThrowableObject; throw requires a single argument: a throwable object , which is an instance of any subclass of the Throwable class throw new ArithmeticException(“Integer division is by 0”); When an exception is thrown, runtime system searches for a catch block to handle the exception. Copyright © 2016 Tech Mahindra. All Rights Reserved.

User Defined Exceptions:

User Defined Exceptions All user defined exception classes should inherit Exception or Throwable Class . They should also override the toString () method and return a meaningful message string, or pass the message string to the superclass constructor . class AgeException extends Exception { public AgeException (String message) { super(message); } } class Employee { public void setAge ( int age) throws AgeException { if(age<18) throw new AgeException (“Age must be > 18”); } } Copyright © 2016 Tech Mahindra. All Rights Reserved.

Best Practices:

Best Practices Be specific while handling the exception in the catch block . Do not use Exception Handling to control programming flow. Use exception handling generously-Very little overhead is imposed by using exception handling mechanism unless an exception occurs. But when an exception occurs it imposes an overhead in terms of execution time. Always use the finally block to release the resources to prevent resource leaks. Handle exceptions locally wherever possible. Do not use Exception handling in loops Avoid writing empty catch blocks Copyright © 2016 Tech Mahindra. All Rights Reserved.

Try it out:

Try it out Q1. Is the following code legal? try { ... } finally { ... } Q2. Code in finally block is executed even in case of unhandled exceptions. (True/False ) Q3. Will the below code compile? try{ ... } catch (Exception e) { ... } catch ( ArithmeticException a) { ... } Q4. NullPointerException exception is thrown from a method when it invokes a method on a reference variable that holds null. But it is not specified in the throws list of the method. It means NullPointerException is a __________ exception Copyright © 2016 Tech Mahindra. All Rights Reserved.

Try it out:

Try it out Q 5. Will the below code compile? try{ int result=98; throw new Exception(); } catch (Exception e){ System.out.println(“Result is “+result); } Copyright © 2016 Tech Mahindra. All Rights Reserved.

Summary:

Summary In this session, we have covered: Introduction to Exceptions Checked & Unchecked Exceptions Using try, catch, finally, throw, throws Predefined exceptions User defined exceptions Copyright © 2016 Tech Mahindra. All Rights Reserved.

Thank you:

Thank you Copyright © 2016 Tech Mahindra. All Rights Reserved.