Week 13 (Exception Handling)
Week 13 (Exception Handling)
in Object-Oriented
Programming (Java)
What is an Exception?
Types of Exceptions
What is an Error
Error vs Exception
What is an Exception Handling
Why we use Exception Handling
Terms used in Exception Handling
Common Scenarios where Exceptions may Occur
User defined Exceptions
What is an Exception?
3
• Checked Exceptions
• Known to compiler at compile time.
• Must be either handled or specified using throws keyword.
• Examples: IOException, FileNotFoundException, etc.
• Unchecked Exceptions
• Not checked at compile time.
• Known to the compiler at runtime, also called runtime Exceptions.
• Examples: ArithmeticException, ArrayIndexOutOfBoundException, etc.
Checked Exception (Example)
5
import java.io.*;
/*The method close() closes the file input stream *
class Example {
It throws IOException*/
public static void main(String args[]) {
FileInputStream fis = null;
fis.close();
/*This constructor FileInputStream(File filename) }
throws FileNotFoundException which is a checked exception */ }
• An Error “indicates serious problems that a reasonable application should not try to catch.”
• Errors are the conditions which cannot get recovered by any handling techniques.
• Examples: Out of memory error, a System crash error, hardware error, StackOverflowError etc.
Error (Example)
8
• java.lang.Object
All Java errors implement the java.lang.Throwable, or
• java.lang.Throwable
are extended from another inherited class therein. The
• java.lang.Exception
full hierarchy of error is:
• java.lang.RuntimeException
• java.lang.Object
• java.lang.ArithematicException
• java.lang.Throwable
• java.lang.NullPointerException
• java.lang.Error
• java.lang.VirtualMachineError
• java.lang.AssertionError
• Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions.
Why we use Exception Handling?
12
• Try-Catch: Piece of code of your program that you want to monitor for exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown. Catch block can catch
this exception and handle it in some logical manner.
• Finally: Any code that absolutely must be executed before a method returns, is put in a finally
block.
• Throw: System-generated exceptions are automatically thrown by the Java run-time system. Now
if we want to manually throw an exception, we have to use the throw keyword.
• 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.
Exception Handling (try-catch)
14
class ExceptionThrown {
// It throws the Exception(ArithmeticException).
//main method
// Appropriate Exception handler is not found within this method.
public static void main(String args[]){
static int divideByZero (int a, int b){ int a = 1;
// this statement will cause ArithmeticException(/ by zero) int b = 0;
int i = a/b;
return i; try {
} int i = computeDivision(a,b);
// The runTime System searches the appropriate Exception handler }
// in this method also but couldn't have found. So looking forward // matching ArithmeticException
// on the call stack. catch (ArithmeticException ex) {
static int computeDivision (int a, int b) { // getMessage will print description of exception(here / by zero)
int res =0; System.out.println(“Message String=“ +ex.getMessage());
try {
res = divideByZero (a,b);
}
} }
// doesn't matches with ArithmeticException
catch (NumberFormatException ex) { }
System.out.println ("NumberFormatException is occured");
} This method is used to get the detail
return res; Output: message of exception as a string value.
} Message String=/ by zero.
Multiple Catch block
15
throw Instance
Example:
throw new ArithmeticException("/ by zero");
Throw Keyword (Example)
17
• If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on.
• If no matching catch is found then the default exception handler will halt the program.
Sequence of Events for throw
18
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Throws Keyword
19
• throws keyword is used in the signature of method to indicate that this method might throw one of the listed type
exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax
exception_list is a comma separated list of all the exceptions which a method might throw.
Scenario:
In any program, if there is a chance of rising an exception then compiler always warn us about it and
compulsorily we should handle that checked exception, Otherwise we will get compile time error saying
unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error
we can handle the exception in two ways:
• The finally keyword is used in association with a try-catch block and guarantees that
a section of code will be executed, even if an exception is thrown.
• The finally block will be executed after the try and catch blocks, but before control
transfers back to its origin.
// Java program to illustrate finally // Case where exceptions occur // and match in the program
class C {
e spo nding
public static void main(String[] args) { d corr
rs a n
int k = 66; tio n occu es
Exce p match
try { o c k
ca tch bl
System.out.println("In try block");
int z = k / 0;
// Carefully see flow dosen't come here Output:
System.out.println("Flow dosen't came here");
} In try block
catch (ArithmeticException e) { In catch block
System.out.println("In catch block"); Dividing by zero but caught
Finally block, Executes whether an exception occurs or not
System.out.println("Dividing by zero but caught");
}
finally {
System.out.println(“Finally block, Executes whether an exception occurs or not");
}
}
}
Common Scenarios where Exceptions may Occur
25
ArithmeticException occurs
int a=50/0; //ArithmeticException
NullPointerException occurs
String s=null;
System.out.println(s.length()); //NullPointerException
NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
User-defined Exceptions
26
• If we can create your own exceptions in Java. Then, keep the following points in mind when writing
your own exception classes.
• If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException class.
• For example, we can define our own Exception class as below: class MyException extends Exception{ }
Finally Block (Example-2)
27
THANK YOU