Exception Handling in Java
Exception Handling in Java
1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur
In this tutorial, we will learn about Java exceptions, it's types, and the
difference between checked and unchecked exceptions.
ADVERTISEMENT
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Do You Know?
o What is the difference between checked and unchecked exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
2) Unchecked Exception
3) Error
Keyword Description
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
JavaExceptionExample.java
Output:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
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.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
But if the application programmer handles the exception, the normal flow
of the application is maintained, i.e., rest of the code is executed.
Example 1
TryCatchExample1.java
Output:
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.
Example 2
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3
In this example, we also kept the code in a try block that will not throw an
exception.
TryCatchExample3.java
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.
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.
TryCatchExample5.java
Output:
Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a
catch block.
TryCatchExample7.java
Output:
Here, we can see that the catch block didn't contain the exception code.
So, enclose exception code within a try block and use catch block only to
handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic
Exception) with a different type of exception class
(ArrayIndexOutOfBoundsException).
TryCatchExample8.java
ADVERTISEMENT
Output:
Example 9
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.
TryCatchExample10.java
ADVERTISEMENT
1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Test it Now
Output:
Points to remember
o At a time only one exception occurs and at a time only one catch
block is executed.
o All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exce
ption occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:
Example 2
MultipleCatchBlock2.java
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exce
ption occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now
Output:
In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is executed.
MultipleCatchBlock3.java
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exce
ption occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now
Output:
Example 4
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.
MultipleCatchBlock4.java
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exce
ption occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now
Output:
Example 5
Let's see an example, to handle the exception without maintaining the
order of exceptions (i.e. from most specific to most general).
MultipleCatchBlock5.java
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 comple
ted");}
9. catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
NestedTryBlock.java
Output:
When any try block does not have a catch block for a particular exception,
then the catch block of the outer (parent) try block are checked for that
exception, and if it matches, the catch block of outer try block is
executed.
If none of the catch block specified in the code is unable to handle the
exception, then the Java runtime system will handle the exception. Then it
displays the system generated message for that exception.
Example 2
Let's consider the following example. Here the try block within nested try
block (inner try block 2) do not handle the exception. The control is then
transferred to its parent try block (inner try block 1). If it does not handle
the exception, then the control is transferred to the main try block (outer
try block) where the appropriate catch block handles the exception. It is
termed as nesting.
NestedTryBlock.java
Output:
Java finally block
Java finally block is a block used to execute important code such as
closing the connection, etc.
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10.System.out.println(e);
11. }
12.//executed regardless of exception occurred or not
13. finally {
14.System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:
TestFinallyBlock1.java
Output:
Let's see the following example where the Java code throws an exception
and the catch block handles the exception. Later the finally block is
executed after the try-catch block. Further, the rest of the code is also
executed normally.
TestFinallyBlock2.java
Output:
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
TestThrow1.java
In this example, we have created the validate method that takes integer
value as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
Output:
TestThrow2.java
1. import java.io.*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\
abc.txt");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. e.printStackTrace();
24. }
25. System.out.println("rest of the code...");
26. }
27. }
Output:
ADVERTISEMENT
TestThrow3.java
Output:
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled
");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18.}
Test it Now
Output:
exception handled
normal flow...
In the above example exception occurs in the m() method where it is not
handled, so it is propagated to the previous n() method where it is not
handled, again it is propagated to the p() method where exception is
handled.
Exception can be handled in any method in call stack either in the main()
method, p() method, n() method or m() method.
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked excepti
on
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handele
d");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18.}
Test it Now
Output:
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Test it Now
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught
or declare the exception.
1. Case 1: We have caught the exception i.e. we have handled the exception
using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword
with the method.
Testthrows2.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16.}
Test it Now
Output:
exception handled
normal flow...
o In case we declare the exception, if exception does not occur, the code
will be executed fine.
o In case we declare the exception and the exception occurs, it will be
thrown at runtime because throws does not handle the exception.
Testthrows3.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare ex
ception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14.}
Test it Now
Output:
B) If exception occurs
Testthrows4.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare ex
ception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14.}
Test it Now
Output:
There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:
Output:
Java throws Example
TestThrows.java
Output:
Java throw and throws Example
TestThrowAndThrows.java
Output:
Difference between final, finally and finalize
The final, finally, and finalize are keywords in Java that are used in
exception handling. Each of these keywords has a different functionality.
The basic difference between final, finally and finalize is that the final is
an access modifier, finally is the block in Exception Handling
and finalize is the method of object class.
Along with this, there are many differences between final, finally and
finalize. A list of differences between final, finally and finalize are given
below:
1. Definition final is the keyword and finally is the block in Java finalize is t
access modifier which is Exception Handling to Java which
used to apply execute the important perform
restrictions on a class, code whether the processing
method or variable. exception occurs or not. object i
collected.
3. Functionali (1) Once declared, final (1) finally block runs the finalize met
ty variable becomes important code even if the cleani
constant and cannot be exception occurs or not. with respect
modified. (2) finally block cleans up before its de
(2) final method cannot all the resources used in
be overridden by sub try block
class.
(3) final class cannot be
inherited.
FinalExampleTest.java
Output:
FinallyExample.java
1. public class FinallyExample {
2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }
Output:
Output: