Exceptions in Java



Exception is a kind of error which happen when a program is running. As a good programmer it should be identified and handled by the programmer. Sometimes it is hard to identify these exceptions before execution. Generally programmer knows about the places that should use exception handling. Some other cases these are identified at the testing stage of a program.   

You need to understand what is the difference between Exception and Error. 



So now you can understand we have to handle exceptions.There are set of exceptions with several ways. Look at this diagram.


Exception hierarchy



Exception hierarchy 
   
I think now you want to see how does an exception appear. Try following example. 

public class TryCatchTest {
 public static void main(String args[]){
  
  int marks[] = new int[2];
   marks[0] = 10;
   marks[1] = 20;
  System.out.println(marks[10]);
 }
}



This program will give ArrayIndexOutOfBoundException. Because I tried to print marks[5] but there are only marks[2]. More about arrays

You can see this as follows in Eclipse.





Now you have a feeling about exceptions. Lets move forward seeking more about exceptions. 


You have seen several colors in above exception hierarchy. These colors are filled with a meaning. We can divide exceptions into three sections as follows. 


  • Checked exceptions
  • Unchecked exceptions ( Run time exceptions )
  • Errors

Before thinking about these things, it is better to have a experience about exception handling. Because it is easy to demonstrate exception behaviors if you know to handle exceptions. 

Exception handling using try-catch block


In above example, you can see how exception appears. Now we are going to feel about Try - catch block. In this case you should have a little bit of knowledge to identify where exception can be occurred. There is two blocks, Try and Catch.
  • Try block is used to define a block of code in which exceptions may occur.
  • Catch blocks are used to handle the exception.
If there is a try block, it is must to have at least one catch block. Try this code.

public class TryCatchTest {
 public static void main(String args[]){
  
  int age[] = new int[2];
  System.out.println(age[10]);
   
  System.out.println("Program is still running");
 }
}



In this example you can see a exception like my first program in this post. This will also give an ArrayIndexOutOfBoundsException. Because you can see my array size is 2, but I asking to give a result for 10th element.

When we get this type of message, the running program will be terminated. That is why you will not able to see the message "Program is still running". This should not happen. We need to run the program skipping these exceptions. This can be done using try-catch block as follows.


public class TryCatchTest {
 public static void main(String args[]){
  
  try {
   int age[] = new int[2];
   System.out.println(age[10]);
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println("Program is still running");
 }
}


This will be messy code. It is the auto generated code by eclipse, but this is the correct form of using try-catch block in a program. I will describe one by one.

Try block


  • As I said try block should be used in the place that exception may occur.
  • You should type it as above program.
  • We saw an exception popped when I was trying to print age[10]. So whole of this code should surround with try block. ( In eclipse you can do it easily. Select the code and press Alt+Shift+z and then select ).
  • You cannot write anything within try block section and catch block section.

Catch block

  • This block execute when exception popped inside the try block. If there is no exception in try block, it skip executing the catch block.
  • Catch block is consist of one bracket. In this bracket I have mentioned "Exception e". What is the meaning of this?


    • In exception hierarchy you can see exception specialization. It means the main class is Throwable then it divide to two sections (Error and Exceptions). 
    • We are not talking about errors. But we have to consider about exceptions. 
    • In exceptions there are few sub classes (IOException, ClassNotFoundException, RuntimeException...etc.).
    • Then again you can see IOExceptions and RuntimeExceptions are divided again into few sub classes. 
    • You can define any of above exception class name to the catch block bracket.
    • There is something called "e". This is a variable which is used to make it easy to handle exception and throw its value. You can use any variable name here. But we generally use e or ex to identify that it is an exception.
    • If you type "Exception" it consider about all exceptions.
    • If you type "NullPointerException" it only consider about This type of exception. 

    • You can use more catch blocks instead of using one block. Then you can grab whatever exception you want.
    • But in Java version 7 and later versions can handle more than one exception in one catch block. You have to use ( | ). But we are not going to talk about this, because in 1Z0-851 examination is for java version 6.

    printStackTrace() method

    • Within catch block you can give any message or whatever you like.
    • But I have used that method (printStackTrace()).
    • This method is used to get the exception that occurs in try block.


    • In following example I have used my own error message instead of using above printStackTrace() method.

    public class TryCatchTest {
     public static void main(String args[]){
      
      try {
       int age[] = new int[2];
       System.out.println(age[10]);
       
      } catch (Exception e) {
       System.out.println("There is an error.");
      }
     }
    }
    
    


    Finally block


    • Finally block is executed when unexpected error has occurred in try block.
    • It runs even though the exception happened or not.
    • This is also used to prevent resource leak with closing file. It is used to close database connections or IO connections

    Examples



    import java.util.*;
    class TryCatchTest{
    
     public static void main(String args[]){
     
      double num1=0, num2=0;//You have to initialize the variables
      Scanner scn = new Scanner(System.in);
      
      try{
       System.out.print("Enter number one: ");
       num1 = scn.nextInt();
      
       System.out.print("Enter number two: ");
       num2 = scn.nextInt();
      
       double div=num1 + num2;
       System.out.println("Answer is : " + div);
      }
      catch(InputMismatchException e){
       System.out.println("Please enter number only.");
      }
      finally{
       System.out.println("Service stopped.");
      }
     }
    }
    
    


    import java.io.*;
    public class TryCatch2{
    
     public static void main(String args[]){
    
      try{
       RandomAccessFile raf = new RandomAccessFile("myfile.txt","r");
       byte b[] = new byte[1000];
       raf.readFully(b,0,1000);
      }
      catch(FileNotFoundException e){
       System.err.println("Error 1");
       System.err.println(e.getMessage());
      }
      catch(IOException e){
       System.err.println("Error 2");
       System.err.println(e.toString());
      }
     }
    }
    
    


    Exceptions in Java Exceptions in Java Reviewed by Ravi Yasas on 9:37 PM Rating: 5

    No comments:

    Powered by Blogger.