Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Jul 6, 2000

Implement Catch All Blocks for Robustness

You can use Throwable class in catch block to catch all kinds of exceptions. This class is the base class of all errors and exceptions in the Java language.

You can use following syntax to catch all exceptions, even if you don't know which ones might be thrown:
 
catch (Throwable t)
{
}
This is the Java equivalent of the C++ syntax:
 
catch (...)
{
}
Here is some sample code:
 
This is how you can use a generic catch all block
to handle array out of bounds error. 
 
static void CatchAllSample(int iIndex)
{
    try
    {
        int a[] = new int[4];
        a[5]= iIndex; // this line throws error
    }
    catch (Throwable e)
    {
        System.out.println("exception: " + e.getMessage());
        e.printStackTrace();
    }
}
This is how you can use a specific catch block to handle the same error. In this case we are using ArrayIndexOutOfBoundsException class to do the exception handling.
 
static void CatchSpecificSample(int iIndex)
{
    try
    {
        int a[] = new int[4];
        a[5]= iIndex; // this line throws error
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
        System.out.println("exception: " + e.getMessage());
        e.printStackTrace();
    }
}
Deepak Pant
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap