^

Exception Handling

The goal of exception handling is to write large and reliable programs so that your programs should not have any error which is remains unhandled. By providing an effective error-handler model using exception handling, Java allows the program code to convey the problems to the client more effectively.
Without exception handling model, you need to write code check a particular error and manage it multiple times at multiple places in your program. Using exception handling, code can be reduced and it also separates the code that performs a specified task from the code that will be executed when the exception is thrown.
One of the interesting aspect of exception handling is that if some run time error occurs, it does not allow the programs to continue on its ordinary path. In fact, it changes the path of execution and reports the user about the error occurred and force the program to handle the error and continue the execution process.
When an exception is thrown, the control is redirected to some place of code to handle the problem, that place is known as exception handler.When an exception is thrown, an Exception object is created on the heap using keyword new. Thus, it can be said that “exceptions are objects”in Java.

Handling Exceptions

To prevent a program from terminating abnormally, you must write the doubtful code inside the guarded region. The guarded region can be created using try block, as shown below.
The guarded region (try block) must be followed by catch block that handles the exception, known as exception handler, as shown below:
real java handling exception
For example:
class WithExp
   {
    public static void main(String args[])
	    {
	     int dnm = args.length;
	     System.out.println(“start”);
	     int num = 8;
	        try 
		   {
		    int res = num/dnm;
		    System.out.println(“Div.Result:” + res);	
		   }
	        catch(ArithmeticException ex)
		      {
 		        System.out.println(“Division by zero is not valid);
              		}
		  System.out.println(“Completed”);
	    }
  }
Instruction Now interpret this program without any command line argument. It generate the following output:
Output:
            Start
            Division by zero is not valid.
            Completed

Java.lang.Throwable Class

All Exception classes are derived from java.lang Throwable class. On next page, you can see the partial hierarchy of classes derived from Throwable class. Throwable class provides a String variable i.e. detailMessage.This variable consists of specific details about the runtime error. For example, for FileNotFound Exception, it consist of the file name that could not be found, and for ArithmeticException it contains “/ by zero” message.
Throwable class provides the following commonly used methods:
  • public String getMessage()
  • This method returns the string message stored in detailMessage variable.
  • public String toString()
  • It returns name of the exception class along with the error message from detailMessage variable.
  • public void printStackTrace()
  • As you have seen in program (StackTrace.java), it shows the information about invoked methods from the runtime stack.
  • public StackTraceElement[] getStackTrace()
  • It returns an array of stack trace elements, each represents one stack frame.

Java.lang.Exception Class

Java.lang.Exception is a subclass of java.lang.Throwable. Class RuntimeException, IOException, SQLException and PrinterException etc are sub classes of Exception class.
It provides the following commonly used constructors:
  • public Exception (String msg)
  • public Exception (Throwable obj)
  • public Exception (String msg, Throwable obj)
When any of the constructors is invoked, it sends the message to the corresponding constructor of java.lang.Throwable class. Actually, the constructors of Throwable class are responsible for creation of Exception object and also sets the string message to detailMessage variable of Throwable

Using finally Block

If an exception is thrown inside a try block and there is no matching catch block then the program terminates without executing remaining lines of code. But some times, it is desirable to execute some code in the following three situations:
  1. When the exception is not thrown.
  2. When the exception is thrown and handled properly.
  3. When the exception is thrown but not handled.
  4. You can put those statements inside finally block as follows:

    Case - 1: When the exception is not thrown:
    real java Exception Finally block
    Case - 2: When the exception is thrown and handled properly:
    real java Exception Finally block throw
    Case - 3: When the exception is thrown, but was not handled:
    real java Exception Finally block throw not
    For Example:
    public class FinallyDemo
      {
       public static void main(String[] args)
        {
          System.out.println(“Start”);
          int dnm=args.length;
          System.out.println(“Number of command line arguments=”+dnm);
          int num=8;
          try
           {
            int res=num/dnm;
            System.out.println(“Result=”+res);
           }
          catch(NullPointerException ex)
           {
             System.out.println(ex.getMessage());
           }
         finally
          {
             System.out.println(“Finally Block executed”);
          }
      System.out.println(“Completed”);
    	}
     }
    Instruction
    Now interpret this program without any command line argument. It generate the following output:
    Output:
            Start
            Number of command line arguments=0
            Finally Block executed
            Exception in thread “main”
            java.lang.ArithmeticException: / by zero at FinallyDemo.main
            (FinallyDemo.java:12)

Using Multiple catch Blocks

A try block can throw different types of exceptions. It depends upon the tasks you perform inside try block. For example, accessing array elements and doing arithmetic operations etc.
If you are using only one catch block, it can handle exception of a specific type. The type depends upon the Exception class specified in parenthesis of catch block.
So to handle multiple exceptions, you should use multiple catch blocks with different Exception Classes in parenthesis, as shown below:
        try {
                ....
                ....
            }
        catch(ExceptionType1 ref)
            {
               .....
               .....
            }
        catch(ExceptionType2 ref)
            {
              .....
              .....
            }
How it works:
  • When Exception object is thrown from try block, then the control goes to the very first catch block and matches its exception type.
  • If it does not match, then control propagates to another catch & repeats the same process.
  • The matching catch block executes and the others are skipped except the finally block.
Implementation:
public class MultipleCatch 
  {
    public static void main(String[] args)
     { 
       int ary[]={20,30, 40};
       System.out.println(“Start”);
       try
       {
         int indx=Integer.parseInt( args[0]);
         int value=ary[indx];
         System.out.println(“Value : “+value + “ at index: “+indx);
       }
      catch(ArrayIndexOutOfBoundsException ex)
       {
         System.out.println(“Invalid Index : “+ex.getMessage());
       }
      catch(NumberFormatException ex)
       {
         System.out.println(“Conversion Error”);
       }
      System.out.println(“End”);
    }
}
  • Test Case-1: Pass “2” as command line argument:
        Output:
    	Start
    	Value: 40 at index: 2
    	End
  • Test Case-2: Pass “5” as command line argument:
        Output:
    	Start
    	Invalid Index:5
    	End	
  • Test Case-3: Pass “first” as command line argument:
        Output:
    	Start
    	Conversion Error
    	End
About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap