Unit5 Exception Handling
Unit5 Exception Handling
Exception Handling
Prepared By
Prof. OM PRAKASH SUTHAR
Assistant Professor, CSE Dept.
Contents
Creating the Exception Object and handling it in the run-time system is called throwing an Exception.
There might be a list of the methods that had been called to get to the method where an exception
occurred. This ordered list of the methods is called Call Stack.
Exception-Handling
Overview
Java’s exception-handling model is based on three operations:
1. Declaring an exception,
2. Throwing an exception, and
3. Catching an exception.
3. System Errors
System errors are thrown by the JVM and are represented in the
Error class. The Error class describes internal system errors, though such
errors rarely occur.
Ex: LinkageError, VirtualMachineError
Exception Types
Exception Types
The finally Clause
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);}
System.out.println("other statement");
}catch(Exception e)
{System.out.println("handeled");} System.out.println("normal flow.."); }
Methods to Print the
Exception Information
1. printStackTrace() import java.io.*;
2. toString() class Main {
3. getMessage() public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
System.out.println(e.toString());
System.out.println(e.getMessage());
}
}
}
Throwing and Catching
Exceptions
Using throw #UserDefined Exception #Explicit
public class Main
{
void checkAge(int age)
{ if(age<18)
throw new ArithmeticException("Not Eligible for voting"); //inside Method UserDefined
else
System.out.println("Eligible for voting");
}
public static void main(String args[])
{
Main obj = new Main();
obj.checkAge(13); Output:
System.out.println("End Of Program"); Exception in thread "main"
} java.lang.ArithmeticException:
Not Eligible for voting
}
at Example1.checkAge(Example1.java:4)
at Example1.main(Example1.java:10)
Throwing and Catching
Exceptions
Example using throws
public class Example1
{
int division(int a, int b) throws ArithmeticException //Method signature, Supports Multiple Exception
{ int t = a/b;
return t;
}
public static void main(String args[]) Output:
{ You shouldn't divide number by zero
Example1 obj = new Example1();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e)
{
System.out.println("You shouldn't divide number by zero");
}
}
}
Rethrowing Exception