Exception Handling in java with example

Exception occurs only at run-time but some exceptions are detected at compile-time and some others at run-time. The exception that are checked at compilation time by the Java Compiler are called 'Checked exceptions' while the exceptions that are checked by the JVM are called 'Unchecked Exceptions'.

       Unchecked exceptions and errors are considered as unrecoverable and the programmer cannot do anything when they occur. The programmer can write a Java program with unchecked exceptions and errors and can compile the program. He can see their effect only when he runs the program.



1
public static void main(String []args) throws IOException

       Here, IOException is an example for checked exception. So, we threw it out of main() method without handling it. This is done by throws clause written after main() method in the above statement.

           
Above diagram explains about the exceptions hierarchy in java. Based on the hierarchy Throwable is the super class of all exceptions in java.
Throwable is a class that represents all errors and exceptions which may occur in Java. Errors and Exceptions all are comes under the super class Throwable. Errors contains all type of errors, Exceptions contains both types called Run-time Exceptions as well as Other Exceptions.

Let us write a program which will show an exception, don't pass any input's through the command prompt.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.javatbrains.exceptions;

public class ArithmericExceptionEx {

     public static void main(String[] args) {
          //Open files
          System.out.println("Open Files");

          //do some processing
          int n = args.length;
          System.out.println("n= "+n);
          int a = 46/n;
          System.out.println("a= "+a);

          //Close files
          System.out.println("Close files");
     }
}
OutPut:
     Open Files
     n= 0
     Exception in thread "main"java.lang.ArithmeticException: / by zero at  com.javatbrains.exceptions.ArithmericExceptionEx.main(ArithmericExceptionEx.java:12)  

Here, division by zero happens and this value represents infinity. This value cannot be stored in any variable. So, there will be an exception at run-time in the above statement. In this case JVM displays exception details and then terminates the program abnormally.
       Here, is the same above example, which we are replacing the double in the place of int and see the output difference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.javatbrains.exceptions;

public class ArithmericExceptionEx {

     public static void main(String[] args) {
          //Open files
          System.out.println("Open Files");

          //do some processing
          double n = args.length;
          System.out.println("n= "+n);
          double a = 46/n;
          System.out.println("a= "+a);

          //Close files
          System.out.println("Close files");
     }
}
OutPut:
     Open Files
     n= 0.0
     a= Infinity
     Close files

       The subsequent statement in the program are not executed. This means that the files which are opened in the program will not be closed and hence the data in the files will be lost. This is the major problem with exceptions. So, how to handle the above problem, continue for knowing the solution.

Exception Handling:
       When there is an exception, the user data may be corrupted. This should be tackled by the programmer by carefully designing the program. For this, he should perform the following 3 steps:

Step 1:
The programmer should observe the statement in his program where there may be a possibility of exceptions. Such statement should be written inside a try block. A try block look like as,

1
2
3
try{
    statements;
}   
The greatness of the try block is that even if some exception arises inside it, the program will not be terminated. When JVM understands that there is an exception, it stores the exception details in an exception exception stack and then jumps into a catch block.

Step 2:
The programmer should write the catch block  where he should displays the exception details to the user. This helps the user to understand that there is some error in the program.

1
2
3
catch(ExceptionClass ref){
    statements;
}
We can display the exception details using any one of the following ways:
·     Using print() or println() method such as System.out.println(ref);
·     Using printStackTrace() method to Throwable class, which fetches exception details from the exception stack and displays them.
Step 3: Lastly the programmer should perform the cleanup operation like closing the files and terminating the threads. The programmer should write this code inside the finally block likes below,


1
2
3
finally{
    statements;
}

The specialty of finally block is that the statements inside the finally block are executed irrespective of whether there is an exception or not.

Ex:
The below program tells the use of try ,catch and finally block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.javatbrains.exceptions;

/*
 *  This class represents the Arithmetic Exception
 *  with try catch block usage
 */
public class AEWithTryCatch {
     public static void main(String[] args) {
          try{
              // Open the files
              System.out.println("Open files");
              // do some processing
              int n = args.length;
              System.out.println("n= "+ n);
              int a = 46 / n;
              System.out.println("a= "+ a);
          } catch(ArithmeticException ae) {
              // display the exception details
              System.out.println(ae);
              // display the message to the user
              System.out
                        .println("Please pass the data while running this program");
          } finally{
              // close the files
              System.out.println("Close files");
          }
     }
}
OutPut:
     Open files
     n= 0
     java.lang.ArithmeticException: / by zero
     Please pass the data while running this program
     Close files       
       In this program, the try block contains the statements where there is possibility for an exception. Where there is an exception, JVM jumps into catch block. The finally block is executed even there is an exception or not.

Handling Multiple Exceptions:


      Most of the times there is possibility of more than one exception present in the program. In this case programmer should write multipe catch blocks to handle each one of them.

       In the previous program, we can intentionally create another exception by adding the code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.javatbrains.exceptions;

/*
 * this is the program which will explaing
 * how to handle multiple exceptions by using
 * try catch blocks
 */
public class MultipleExceptions {
     public static void main(String[] args) {
          try{
              // Open the files
              System.out.println("Open files");
              // do some processing
              int n = args.length;
              System.out.println("n= "+ n);
              int a = 46 / n;
              System.out.println("a= "+ a);
              int b[] = { 10, 20, 30 };
              b[50] = 100;
          } catch(ArithmeticException ae) {
              // display the exception details
              System.out.println(ae);
              // display the message to the user
              System.out
                        .println("Please pass the data while running this program");
          } catch(ArrayIndexOutOfBoundsException aie) {
              // display the exception details
              aie.printStackTrace();
              // display the message to the user
              System.out
                        .println("Please pass the array index is within the range");
          } finally{
              // close the files
              System.out.println("Close files");
          }
     }
}
OutPut:
     Open files
     n= 0
     java.lang.ArithmeticException: / by zero
     Please pass the data while running this program
     Close files

From the preceding discussion, we can conclude that:
·     An exception can be handled using try, catch and finally blocks.
·     It is possible to handle multiple exceptions using multiple catch blocks.
·     Even though there is possibility for several exceptions in try block, at a time only one exception will be raised.
·     A single try block can be followed by several catch blocks.
·     We cannot write a catch block without try block, but we can write a try without any catch block.
·     It is not possible to insert some statements between try and catch blocks.
·     It is possible to write a try block with in another try block. They are called nested try blocks.

throws clause:
       In case the programmer does not want to handle the checked exceptions, he should throw them out using throws clause. Otherwise there will be an error flagged by Java Compiler.

       Where there is an IOException raised by readLine() method of BufferedReader class. This is checked exception and hence the compiler checks it at the compilation time. If it is not handled, the compiler expects at least to throw it out.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.javatbrains.exceptions;

/*This program represents the IOException*/
import java.io.*;

class Sample{
    
         //instance variable
         private String name;
         //method to accept name
         void accept(){
                //to accept data from keyboard
                BufferedReader br = newBufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter name: ");
                name= br.readLine();
         }
         //method to display name
         void display(){
                System.out.println("Name: "+name);
         }
}

public class IOExceptionEx {
     public static void main(String[] args){
        Sample s = new Sample();
        s.accept();
        s.display();
     }

}
OutPut:
IOExceptionEx.java: <Line Number>: unreported exception java.io.IOException; must be caught or declared to the thrown
          name = br.readLine();

            In this java program compiler expects the programmer to handles the IOException using try and catch blocks or should throw out the IOException without handling it. We should throw it out the using throws clause,
1
throws IOException
           
rewriting the above program by handling the IOException. It will execute without any problem.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.javatbrains.exceptions;

/*This program represents the IOException*/
import java.io.*;

class Sample{
    
         //instance variable
         private String name;
         //method to accept name
         void accept() throws IOException{
                //to accept data from keyboard
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter name: ");
                name= br.readLine();
         }
         //method to display name
         void display(){
                System.out.println("Name: "+name);
         }
}

public class IOExceptionEx {
     public static void main(String[] args) throws IOException {
          Sample s = new Sample();
          s.accept();
          s.display();
     }

}
//OutPut:
     Enter name:
      JavaTBrains
      Name: JavaTBrains

throw clause:
       There is a throw statement available in java to throw an exception explicitly and catch it.

       In the following program we are creating an object of NullPointerException class and throwing it out of try block,


1
throw new NullPointerException("Exception data");

            In the above statement NullPointerException object is created and Exception data is stored into its object. Then it is thrown using throw statement. Now, we can catch it by using catch block as,
1
catch(NullPointerException ne){}

            Here, is the Null poiner exception example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.javatbrains.exceptions;

class Sample1 {
     static void demo() {
          try{
              System.out.println("Inside demo()");
              throw new NullPointerException("Exception Data");
          } catch(NullPointerException ne) {
              System.out.println(ne);
          }
     }
}

public class NullPointerExceptionEx {

     public static void main(String[] args) {
          Sample1.demo();
     }

}
//OutPut:
     Inside demo()
     java.lang.NullPointerException: Exception Data

throw clause uses:
·     throw clause is used in software testing to test whether a program is handling all the exceptions as claimed by the programmer.
·     throw clause can be used to throw our own exceptions also.
Types of Exceptions:
       Following are the exceptions available in Java:
·     Built-in exceptions
·     User-defined exceptions
Built-in Exceptions:
       Built-in exceptions are the exceptions which are already available in Java. These exceptions are suitable to explain certain error situations.
The important built-in exceptions in Java are,
·     ArithmeticException: thrown when an exceptional condition has occured in an arithmetic operation.
·     ArrayIndexOutOfBoundException: thrown to indicate than an array has been accessed with an illegal index. The index either negative or greater than or equal to the size of the array.
·     ClassNotFoundException: this exception is raised when we try to access a class whose definition is not found.
·     FileNotFoundException: raised when a file is not accessible or does not open.
·     IOException: thrown when an input-output operation is failed or interrupted.
·     InterruptedException: thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
·     NoSuchFieldException: thrown when a class does not contain the field specified.
·     NoSuchMethodException: thrown when accessing a method which is not found.
·     NullPointerException: raised when referring to the members of a null object. null represents nothing.
·     NumberFormatException: raised when a method could not convert a String into a numeric format.
·     RuntimeException: this represents any exception which occurs during runtime.
·     StringIndexOutOfBoundException: thrown by String class method to indicate that an index is either negative or greater than the size of the string.

Do you know?

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example