Exception Handling
Exception Handling
Handling in JAVA
Outline
2
◻ What is an Exception
◻ Types of Exceptions
◻ What is an Error
◻ Error vs Exception
◻ What is an Exception Handling
◻ Why we use Exception Handling
What is an Exception?
3
• Exceptions are recoverable using try, catch, throw, and throws keywords.
• Checked Exceptions
• Known to compiler at compile time.
• Must be either handled or specified using throws keyword.
• Examples: IOException, FileNotFoundException, etc.
• Unchecked Exceptions
• Not chekced at compile time.
• Known to the compiler at runtime, also called runtime Exceptions.
• Examples: ArithmeticException, ArrayIndexOutOfBoundException,
etc.
Checked Exception (Example)
6
• Errors are the conditions which cannot get recovered by any handling
techniques.
Error Exception
• 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
• What
• Why
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. If they are not , a compile-time error will
result.
Exception Handling (try-catch example slide-1)
17
class ExceptionThrown
// The runTime System searches the appropriate Exception
{ handler
// in this method also but couldn't have found. So looking
// It throws the
Exception(ArithmeticException). forward
// Appropriate Exception handler is not found // on the call stack.
within this method. static int computeDivision (int a, int b)
{
static int divideByZero (int a, int b) int res =0;
{ try
{
// this statement will cause res = divideByZero (a,b);
ArithmeticException(/ by zero) }
int i = a/b; // doesn't matches with ArithmeticException
return i; catch (NumberFormatException ex)
} {
System.out.println ("NumberFormatException is
occured");
}
return res;
}
Exception handling (try-catch example slide-2)
18
//main method
public static void main(String args[])
{
int a = 1;
int b = 0;
try
{
int i = computeDivision(a,b);
Output:
}
// matching ArithmeticException Message String=/ by
catch (ArithmeticException ex) zero.
{
// getMessage will print description of exception(here / by zero)
System.out.println(“Message String=“ +ex.getMessage());
}
}
Syntax
throw Instance
Example:
throw new ArithmeticException("/ by zero");
Throw Keyword (Example)
21
//main method
// Java program that demonstrates the use of throw
class ThrowExcep public static void main(String args[])
{ {
try
static void fun()
{
{ fun();
try }
{ catch(NullPointerException e)
throw new NullPointerException("demo"); {
} System.out.println("Caught in main.");
catch (NullPointerException e) }
}
{
System.out.println("Caught inside fun().");
throw e; }
// re-throwing the exception
}
} Output:
Caught inside fun().
Caught in main.
Throw Keyword (Example Explanation)
22
• The flow of execution of the program stops immediately after the throw
statement is executed and the nearest enclosing try block is checked to see if
it has a catch statement that matches the type of exception.
• If no matching catch is found then the default exception handler will halt the
program.
Sequence of Events for throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Throws Keyword
24
Syntax
Scenario:
In anyprogram, 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 block will be executed after the try and catch blocks,
but before control transfers back to its origin.
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
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{ }
User-defined Exception (Example)
/* This is my Exception class, I have named it class Example1
MyException * you can give any name, just {
public static void main(String args[])
remember that it should * extend Exception class */
{
try
class MyException extends Exception { System.out.println("Starting of try block");
{ // I'm throwing the custom exception using throw
String str1; throw new MyException("This is My error Message");
/* Constructor of custom exception class * here I am }
copying the message that we are passing while * catch(MyException exp)
{
throwing the exception to a string and then
System.out.println("Catch Block") ; System.out.println(exp) ;
displaying * that string along with the message. */ }
}
MyException(String str2) }
{ str1=str2; }
public String toString()
{ return ("MyException Occurred: "+str1) ; }
} Output:
Starting of try block
Catch Block
MyException Occurred: This is My
error Message
35
Thanks