Exception Handling
Exception Handling
1
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error
is considered as the unchecked exception. However, according to Oracle,
there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
2
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For example,
IOException, SQLException, etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
3) Error
Java provides five keywords that are used to handle the exception. The
following table describes each.
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.
3
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Output:
11. Exception in thread main java.lang.ArithmeticException:/
by zero
12. rest of the code...
There are given some scenarios where unchecked exceptions may occur.
They are as follows:
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
4
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
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 catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent
class exception ( i.e., Exception) or the generated exception type. However,
the good approach is to declare the generated type of exception.
5
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:
But if the application programmer handles the exception, the normal flow of
the application is maintained, i.e., rest of the code is executed.
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).
Note: if an exception occurs in the try block, the rest of the block
code will not execute.
Example 4
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
7
TryCatchExample5.java
Output:
Example 6
TryCatchExample6.java
8
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Output:
25
Example 8
9
Exception in thread "main" java.lang.ArithmeticException: / by
zero
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.
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.
10
In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is executed.
Output:
Arithmetic Exception occurs
rest of the code
Example
11
1. public class MultipleCatchBlock4 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. System.out.println(s.length());
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occ
urs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
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. }
12
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 co
mpleted");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
13
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as
nested try block. Every statement that we enter a statement in try block,
context of that exception is pushed onto the stack.
Example 1
Let's see an example where we place a try block within another try block for
two different exceptions.
NestedTryBlock.java
14
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }
15
Java finally block
Java finally block is a block used to execute important code such as closing
the connection, etc.
Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).
16
Usage of Java finally
Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.
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. }
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception
however the catch block cannot handle it. Despite this, the finally block is
executed after the try block and then the program terminates abnormally.
17
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.
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).
18
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom
exceptions making the code recovery and debugging easier.
We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number. Here, we just
need to set the condition and throw exception using throw keyword.
19
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.
Output:
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
20
Note: Every subclass of Error and RuntimeException is an unchecked exception in
Java. A checked exception is everything else under the Throwable class.
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");
Output:
21
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
22
26. }
27.}
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.}
Output:
23
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 exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
24
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Testthrows1.java
1. import java.io.IOException;
25
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
26
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. }
27
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
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 exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14.}
Test it Now
Output:
28
Difference between throw and throws in
Java
The throw and throws is the concept of exception handling where the throw
keyword throw the exception explicitly from a method or a block of code
whereas the throws keyword is used in signature of the method.
There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:
29
method. For
example, main()
throws IOException,
SQLException.
Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e. Exception
class that can be obtained using getMessage() method on the object we
have created.
In this section, we will learn how custom exceptions are implemented and
used in Java programs.
30
2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }
Note: We need to write the constructor that takes the String as the error message
and it is called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code,
constructor of InvalidAgeException takes a string as an argument. This string
is passed to constructor of parent class Exception using the super() method.
Also the constructor of Exception class can be called without using a
parameter and calling super() method is not mandatory.
TestCustomException1.java
31
24. }
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. System.out.println("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. System.out.println("Exception occured: " + ex);
41. }
42.
43. System.out.println("rest of the code...");
44. }
45.}
Output:
Example 2:
TestCustomException2.java
32
5. }
6.
7. // class that uses custom exception MyCustomException
8. public class TestCustomException2
9. {
10. // main method
11. public static void main(String args[])
12. {
13. try
14. {
15. // throw an object of user defined exception
16. throw new MyCustomException();
17. }
18. catch (MyCustomException ex)
19. {
20. System.out.println("Caught the exception");
21. System.out.println(ex.getMessage());
22. }
23.
24. System.out.println("rest of the code...");
25. }
26.}
Output:
33