Exception-Handling-In-Java (Join AICTE Telegram Group)
Exception-Handling-In-Java (Join AICTE Telegram Group)
Java
An object of
exception class exception
Int data=10/0; is thrown object
No Is Yes
handled
?
JVM
1)Prints out exception Rest of the code is
description executed
2) Prints the stack trace
3) Terminate the program
Try-catch Block
try{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Multiple catch
try { //Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
……
Sequence of Events
Preceding step
try block
statement
unmatched catch
matching catch
unmatched catch
next step
class Example2{
public static void main(String args[]){
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:ArrayIndexOutOfBoundsException"); }
catch(Exception e){
System.out.println("Warning: Some Other exception"); }
no Exception Yes
Occurred ?
no Yes
Exception
Handled ?
Preceding step
try block
statement
unmatched catch
matching catch
unmatched catch
finally
next step
class Simple{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
} }
Throwing our Own Exceptions
throw keyword
• In java we have already defined exception classes such as
ArithmeticException, NullPointerException etc.
void method_name() throws exception_class_name
{
...
}
import java.io.*;
class M {
void method() throws IOException{
throw new IOException("device error");
}
}
class Test{
public static void main(String args[])throws IOException{
Test t=new Test();
t.method();
System.out.println("normal flow...");
}
}
throw keyword throws keyword
throw is used to explicitly throw an throws is used to declare an
exception. exception.
checked exception can not be checked exception can be propagated
propagated without throws. with throws.
throw is followed by an instance. throws is followed by class.
throw is used within the method. throws is used with the method
signature.
You cannot throw multiple You can declare multiple exception
exception e.g.
public void method()throws
IOException,SQLException.
Common Questions
1. What is exception? How it is handled? Explain with
suitable example.
2. Explain following terms with respect to exception
1. try
2. catch
3. throw
4. Finally
3. What are different types of errors? What is use of
throw, throws, finally.
4. Write a program to throw a user defined exception
“String Mismatch” if two strings are not equal.