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();
}
}