Warning: Invalid argument supplied for foreach() in /home/techrecipes/public_html/wp-content/themes/techrecipes/header.php on line 77

Java: Exceptions – Try, Catch and Finally

The following Tech-Recipes tutorial contains a method-by-method handling of errors and exceptions.


It should be noted that all exceptions that can be generated are subclasses of the class. java.lang.throwable.Exception. With this in mind and the idea of a hierarchy of errors, it is possible to write effective and working exception Try, Catch and Finally blocks.

When adding the exceptions, the order in which they appear MUST be in an upward order. What this means is that you work from lower subclasses towards the superclass Exception.
If theses exceptions are written in the opposite order, then the lower catch blocks are useless since a superclass will catch exceptions found in its subclasses.

The following is an example of what not to do:
try{}
catch(Exception e){}
catch(IOException e){}
*In this case, Exception is the top class and is above IOException. The code within IOException will NEVER be executed, even in the instance of an IO error, since Exception will handle all errors.

The correct way to do the above is as follows:
try{}
catch(IOException e){}
catch(Exception e){}
*Now IO exceptions will be caught by the first catch block and all other exceptions handled by the superclass Exception.

I will now use a runnable example, trying to output 1 divided by 0.

public class Exceptions{
public static void main(String args[]){
try{
System.out.println(1/0);
}
catch(java.lang.ArithmeticException e){
System.out.println(“The operation is not possible.”);
/*Note I used ArithmeticException here, but i could have just as easily used Exception */
}
}
}

This example runs a Try on the operation 1/0, knowing this operation will cause an error. However, try blocks should be added to methods, or sections of methods which are likely to cause errors.
Once the error occurs, Java decides what to do. In this case, since we have the Catch block, Java knows that this is the code we want to run, in the case of an error, in the corresponding Try block.

The Try/Catch has more uses than just this. It is an essential debugging tool. Since the method has a parameter, this parameter is an instance of the exception that just occured, and we can retrieve vital infomation from it.
Here is the same example with some of these debugging options added:
public class Exceptions{
public static void main(String args[]){
try{
System.out.println(1/0);
}
catch(java.lang.ArithmeticException e){
System.out.println(“A Stack Trace of the Error:”);
e.printStackTrace();
//e.getMessage(); //This one is useable when we write our own exceptions
System.out.println(“The operation is not possible.”);
}
}
}

*Notice the extra lines in the output.
We now know what the error was and where it occured, without ending out program. If there had been more code to execute, this program would have continued after giving us this information.

I will soon write a tech-recipe to deal with e.getMessage(), when writing our own exception classes.

Finally, I will explain the Finally Exception:
This addition to the Try/Catch family is a set of code that will be executed no matter what. If there is an error, the catch block is run, and then the finally block. If there is no error, the try block will be run and then the finally block.

The code contained within the Finally block needs to be simple and guarenteed not to crash, as it is outside the catch block’s scope and cannot be send back to handle any errors.

CODE example of TRY, CATCH and FINALLY:
public class Exceptions{
public static void main(String args[]){
try{
System.out.println(“Try Block before the error.”);
System.out.println(1/0);
System.out.println(“Try Block after the error.”); //this line will not print
}
catch(java.lang.ArithmeticException e){
System.out.println(“Catch Block”);
System.out.println(“A Stack Trace of the Error:”);
e.printStackTrace();
//e.getMessage(); //This one is useable when we write our own exceptions
System.out.println(“The operation is not possible.”);
}
finally{
System.out.println(“Finally Block”);
}
}
}

Your output should be as follows:
*
Try Block before the error.
Catch Block
A Stack Trace of the Error:
java.lang.ArithmeticException: / by zero
at Exceptions.main(Exceptions.java:5)
The operation is not possible.
Finally Block
*
The print statement after the error within the try block was not printed as the exception caused control to be moved to the catch block. But no matter which block has control and for how long, the finally block WILL be run after one of them has completed.

Questions/Comments: [email protected]
-William. § (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.

  • Aparna

    What if an error encounters in catch block or finally block?

  • bujjibabu

    try{
    System.out.println(“11111111grfghtyhty”);
    CustomerPostRequestForm customerForm = (CustomerPostRequestForm)form;
    PropertyDelegate pd = new PropertyDelegate();
    Collection states = pd.getStates();
    request.setAttribute(“statesCollection”, states);

    int typeid =Integer.parseInt(request.getParameter(“managemen11111111111111111111111111111111t33333333333333333333333337777777777777777777777777777777777″));
    System.out.println(“show the error”+typeid);
    if(typeid == 1)
    customerForm.setRequesttype(“Request for Property Management”);
    if(typeid == 2)
    customerForm.setRequesttype(“Request for Documentation Services”);
    if(typeid == 3)
    customerForm.setRequesttype(“Request for Tax Assistance”);
    if(typeid == 4)
    customerForm.setRequesttype(“Request for Rent Agreement”);
    if(typeid == 5)
    customerForm.setRequesttype(“Request for Sales Agreement”);
    if(typeid == 6)
    customerForm.setRequesttype(“Legal Advice”);
    if(typeid == 7)
    customerForm.setRequesttype(“Investment Advice”);
    if(typeid == 8)
    customerForm.setRequesttype(“Insurance Advice”);
    if(typeid == 9)
    customerForm.setRequesttype(“Financial Advice”);
    if(typeid == 10)
    customerForm.setRequesttype(“Request for Signature websites”);
    if(typeid == 11)
    customerForm.setRequesttype(“Request for Marketing colabrate”);
    if(typeid == 12)
    customerForm.setRequesttype(“online banners”);
    if(typeid == 13)
    customerForm.setRequesttype(“Request for Property Valuation”);
    if(typeid == 14)
    customerForm.setRequesttype(“Request for General Advice”);
    customerForm.setReq_type(typeid);
    customerForm.setCheck(5);
    return mapping.findForward(SUCCESS);
    }
    catch(Exception e){
    System.out.println(“1111111111″);
    System.out.println(“Headername::”+ request.getRequestURL());
    HttpSession session = request.getSession();
    String userId = (String)session.getAttribute(“Customername”);
    String exception=””+e.getCause();
    if(exception != null)
    exception.toString();
    String url=request.getRequestURL().toString();
    System.out.println(“Costomername:”+(userId));
    System.out.println(“Costomername:”+(userId));

    Date da = new Date();

    String date=da.toString();
    System.out.println(“Costomername:##############################”+(date));
    ErrorDAO ed = new ErrorDAO();
    ed.storeExection(userId,exception,url,date);
    return mapping.findForward(SUCCESS);
    }
    i have created an error in try block must it was not showing error to me can u give me a reason y its not showing..

  • Indra Reddy

    we can write catch block in the try block?

    • dave sachin

      no..indra thats the impossible..we cant write the catch block in the try block………….