Exception Handling
Exception Handling
Exception Handling
Exception Handling
• The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
• In Java, an exception is an event that disrupts the normal flow of the program.
1.try{
2.//code that may throw an exception
3.}finally{}
• In this example, we also kept the code in a try block that will not throw an exception.
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
• Let's see an example to handle checked exception.
1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3. public class TryCatchExample10 {
4. public static void main(String[] args) {
5. PrintWriter pw;
6. try {
7. pw = new PrintWriter("jtp.txt"); //may throw exception
8. pw.println("saved");
9. }
10.// providing the checked exception handler
11. catch (FileNotFoundException e) {
12. System.out.println(e);
13. }
14. System.out.println("File saved successfully");
15. }
16.}
• Output:
• File saved successfully
Multiple catch blocks
• A try block can be followed by one or more catch blocks.
• Each catch block must contain a different exception handler.
• So, if you have to perform different tasks at the occurrence of different
exceptions, use java multi-catch block.
• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
1. public class MultipleCatchBlock1 {
2. public static void main(String[] args) {
3. try {
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e) {
8. System.out.println("Arithmetic Exception occurs");
9. }
10. catch(ArrayIndexOutOfBoundsException e) {
11. System.out.println("ArrayIndexOutOfBounds Exception occurs");
12. }
13. catch(Exception e) {
14. System.out.println("Parent Exception occurs");
15. }
16. System.out.println("rest of the code");
17. }
18.}
• Output -- Arithmetic Exception occurs
• rest of the code
1. public class MultipleCatchBlock2 {
2. public static void main(String[] args) {
3. try {
4. int a[]=new int[5];
5. System.out.println(a[10]);
6. }
7. catch(ArithmeticException e) {
8. System.out.println("Arithmetic Exception occurs");
9. }
10. catch(ArrayIndexOutOfBoundsException e) {
11. System.out.println("ArrayIndexOutOfBounds Exception occurs");
12. }
13. catch(Exception e) {
14. System.out.println("Parent Exception occurs");
15. }
16. System.out.println("rest of the code");
17. }
18.}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
In this example, try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed.
1. public class MultipleCatchBlock3 {
2. public static void main(String[] args) {
3. try {
4. int a[]=new int[5];
5. a[5]=30/0;
6. System.out.println(a[10]);
7. }
8. catch(ArithmeticException e) {
9. System.out.println("Arithmetic Exception occurs");
10. }
11. catch(ArrayIndexOutOfBoundsException e) {
12. System.out.println("ArrayIndexOutOfBounds Exception occurs");
13. }
14. catch(Exception e) {
15. System.out.println("Parent Exception occurs");
16. }
17. System.out.println("rest of the code");
18. }
19.}
Output:
Arithmetic Exception occurs
rest of the code
• In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In such
case, the catch block containing the parent exception class Exception will invoked.
1. public class MultipleCatchBlock4 {
2. public static void main(String[] args) {
3. try{
4. String s=null;
5. System.out.println(s.length());
6. }
7. catch(ArithmeticException e) {
8. System.out.println("Arithmetic Exception occurs");
9. }
10. catch(ArrayIndexOutOfBoundsException e) {
11. System.out.println("ArrayIndexOutOfBounds Exception occurs");
12. }
13. catch(Exception e) {
14. System.out.println("Parent Exception occurs");
15. }
16. System.out.println("rest of the code");
17. }
18.}
• Output:
• Parent Exception occurs
• rest of the code
• Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).
1.class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 complet
ed");}
10. System.out.println("rest of the code...");
11. }
12.}
• Output – compile time error
Nested try/catch
• In Java, using a try block inside another try block is permitted. It is called as nested try
block.
• For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
....
//main try block
try {
statement 1;
statement 2;
//try catch block within another try block
try {
statement 3;
statement 4;
//try catch block within nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//exception message
}
}
catch(Exception e1) {
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Java Nested try Example
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try {
//inner try block 1
try {
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e) {
System.out.println(e);
}
//inner try block 2
try {
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e) {
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
• Output:
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..
public class NestedTryBlock2 {
public static void main(String args[]) {
// outer (main) try block
try {
//inner try block 1
try {
// inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out of its bounds
System.out.println(arr[10]);
}
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
• Output:
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 4 outer
(main) try block
Throw keyword
• The Java throw keyword is used to throw an exception explicitly.
• We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
• We can also define our own set of conditions and throw an exception explicitly using
throw keyword.
• Here, we just need to set the condition and throw exception using throw keyword.
• The syntax of the Java throw keyword is given below.
• throw new exception_class("error message");
• Let's see the example of throw IOException.
• throw new IOException("sorry device error");
• Throwing Unchecked Exception
• In this example, we have created a method named validate() that accepts an integer as a parameter. If the age is less than 18, we are
throwing the ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Throws keyword
• Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}
Advantages –
• Now Checked Exception can be propagated
• It provides information to the caller of the method about the exception.
• It gives an information to the programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling code so
that the normal flow of the program can be maintained.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
} catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Case 1: Handle Exception Using try-catch block
• In case we handle the exception, the code will be executed fine whether exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output
exception handled
normal flow...
Case 2: Declare Exception
• Two sub-cases
• In case we declare the exception, if exception does not occur, the code will be
executed fine.
• In case we declare the exception and the exception occurs, it will be thrown
at runtime because throws does not handle the exception.
• If exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
device operation performed
normal flow...
• If exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Java Custom Exception
• In Java, we can create our own exceptions that are derived classes of the Exception
class.
• Creating our own Exception is known as custom exception or user-defined exception.
• Basically, Java custom exceptions are used to customize the exception according to
user need.
• Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
• In order to create custom exception, we need to extend Exception class that belongs
to java.lang package.
// class representing custom exception // main method
class InvalidAgeException extends Exception { public static void main(String args[]) {
public InvalidAgeException (String str) { try {
// calling the constructor of parent Exception // calling the method
super(str); validate(13);
} }
} catch (InvalidAgeException ex) {
// class that uses custom exception InvalidAgeException System.out.println("Caught the exception");
public class TestCustomException1 { // printing the message from InvalidAgeException object
// method to check the age System.out.println("Exception occured: " + ex);
static void validate (int age) throws InvalidAgeException { }
if(age < 18) { System.out.println("rest of the code...");
// throw an object of user defined exception }
throw new InvalidAgeException("age is not valid to vote"); }
}
else {
System.out.println("welcome to vote");
}
}
// class representing custom exception // class that uses custom exception MyCustomException
class MyCustomException extends Exception public class TestCustomException2
{ {
// main method
public static void main(String args[])
}
{
try
{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
inprotected.com