Menu
Topics Index
...
`


Exceptions >
Siva Nookala - 20 Feb 2017
We can use the simplest form of the exception handling, the try-catch block to efficiently communicate the exceptions thrown by the methods.

We will use the ValuableResource class discussed in Exception Handling In Java with Example Program.
try
{
    ValuableResource vr = new ValuableResource();
    vr.initialize();
    vr.useTheResource(); // LINE A
    vr.useItInAnotherWay();
    vr.close();
}
catch(Exception ex)
{
     // This is for program administrator/support
    ex.printStackTrace();
    // This is for the user.
    System.out.println("There was a problem while using the valuable resource.");
}
Here, we have put all the code which might throw an exception in the try block and in the corresponding catch block, we caught the exception, logged the stack trace using printStackTrace and given an understandable message for the user. Depending upon the type of application, there could be a different set of actions we perform in the catch block.
Please note that the printStackTrace method prints the details of exception like class, method, file name, line number and the order in which they are called. This information is very useful for debugging of the exceptions.
One drawback of this program is that it does not close the resource when the exception occurs. We know that when an exception occurs, the statements below that will not be executed. So if the exception occurs at LINE A, then the statements below it useItInAnotherWay and close will not be called. We also know that we have to close the resource properly after using it by calling the close method. So we will also call the close method in the catch-block. The modified program will look like.
ValuableResource vr = new ValuableResource();
try
{
    vr.initialize();
    vr.useTheResource(); // LINE A
    vr.useItInAnotherWay();
    vr.close(); // Calls close when no exception occurs
}
catch(Exception ex)
{
     // This is for program administrator/support
    ex.printStackTrace();
    // This is for the user.
    System.out.println("There was a problem while using the valuable resource.");
    vr.close(); // Calls close when exception occurs
}
One other drawback of this program is, when we are using the resource the resource might throw a NullPointerException, ArithmeticException or an ArrayIndexOutOfBoundsException. But here we are catching all types of exceptions using a single catch-block and giving the same message to the user. Java Multiple Catch Block With Example Program explains how we can handle different types of exceptions in a different way.

Dependent Topics : Why Java Throws Exceptions  Abstraction in Java 

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App