Exception Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

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.

• Exception is an abnormal condition.

• In Java, an exception is an event that disrupts the normal flow of the program.

• It is an object which is thrown at runtime.


Advantage of Exception Handling
• The core advantage of exception handling is to maintain the normal flow of the
application.
• An exception normally disrupts the normal flow of the application;
• Let's consider a scenario:
• statement 1;
• statement 2;
• statement 3;
• statement 4;
• statement 5; //exception occurs
• statement 6;
• statement 7;
• statement 8;
• statement 9;
• statement 10;
• Suppose there are 10 statements in a Java program and an exception occurs at
statement 5;
• The rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed.
• However, when we perform exception handling, the rest of the statements will be
executed.
Types of Java Exceptions

• There are mainly two types of exceptions: checked and unchecked


• Checked Exceptions
• The classes that directly inherit the Throwable class except RuntimeException are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
• Un-Checked Exceptions
• The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Hierarchy of Java Exception classes
Java catch block
• Default catch mechanism
• In java, there’s a default catch mechanism available.
• If you are not writing any code for handling exceptions. This default catch
mechanism works automatically.
• But the problem is, your programs will get stop execute as soon as the control shifts
from the statement (generating exception) to default catch.
• We want that –firstly we’ll get the run time error/exception message properly
related to exception and the program should get executed completely.
• Will our program be robust ? (control will never return back to the program again).
The JVM firstly checks whether the exception is handled
or not. If exception is not handled, JVM provides a default
exception handler that performs the following tasks:

Prints out exception description.

Prints the stack trace (Hierarchy of methods where the


exception occurred).

Causes the program to terminate.

But if the application programmer handles the exception,


the normal flow of the application is maintained, i.e., rest
of the code is executed.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
1. public class TryCatchExample1 {
2. public static void main(String[] args) {
3. int data=50/0; //risky statement (may throw exception)
4. System.out.println("rest of the code");
5. }
6. }
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


• As displayed in the above example, the rest of the code is not executed (in such case, the rest of the code statement
is not printed).
• There might be 100 lines of code after the exception. If the exception is not handled, all the code below the exception
won't be executed.
Solution by exception handling
• Let's see the solution of the above problem by a java try-catch block.
1. public class TryCatchExample2 {
2. public static void main(String[] args) {
3. try {
4. int data=50/0; //may throw exception
5. }
6. //handling the exception
7. catch(ArithmeticException e) {
8. System.out.println(e);
9. }
10. System.out.println("rest of the code");
11. }
12.}
Output:
• java.lang.ArithmeticException: / by zero
• rest of the code
• As displayed above, the rest of the code is executed, i.e., the rest of the code statement is printed.
Java try block
• Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
• If an exception occurs at the particular statement in the try
block, the rest of the block code will not execute.
• So, it is recommended not to keep the code in try block that will
not throw an exception.
• Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
1.try{
2.//code that may throw an exception
3.}catch(Exception_class_Name ref){}

Syntax of try-finally block

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.

1. public class TryCatchExample3 {


2. public static void main(String[] args) {
3. try {
4. int data=50/0; //may throw exception
5. // if exception occurs, the remaining statement will not execute
6. System.out.println("rest of the code");
7. }
8. // handling the exception
9. catch(ArithmeticException e) {
10. System.out.println(e);
11. }
12. }
13.}
• Output:
• java.lang.ArithmeticException: / by zero
• Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.
• Let's see an example to print a custom message on exception.
1. public class TryCatchExample5 {
2. public static void main(String[] args) {
3. try {
4. int data=50/0; //may throw exception
5. }
6. // handling the exception
7. catch(Exception e) {
8. // displaying the custom message
9. System.out.println("Can't divided by zero");
10. }
11. }
12.}
• Output:
• Can't divided by zero
• In this example, we handle the generated exception (Arithmetic Exception) with a different
type of exception class (ArrayIndexOutOfBoundsException).

1.public class TryCatchExample8 {


2. public static void main(String[] args) {
3. try {
4. int data=50/0; //may throw exception
5. }
6. // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
7. catch(ArrayIndexOutOfBoundsException e) {
8. System.out.println(e);
9. }
10. System.out.println("rest of the code");
11. }
12.}
• Output:
• Exception in thread "main" java.lang.ArithmeticException: / by zero
• Let's see an example to handle another unchecked exception.

1. public class TryCatchExample9 {


2. public static void main(String[] args) {
3. try {
4. int arr[]= {1,3,5,7};
5. System.out.println(arr[10]); //may throw exception
6. }
7. // handling the array exception
8. catch(ArrayIndexOutOfBoundsException e) {
9. System.out.println(e);
10. }
11. System.out.println("rest of the code");
12. }
13.}

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());
}

System.out.println("rest of the code...");


}
}

inprotected.com

You might also like