devxlogo

Implement Catch All Blocks for Robustness

Implement Catch All Blocks for Robustness

You can use Throwable class in catch block to catchall kinds of exceptions. This class is the base classof 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 blockto 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();    }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist