| In some cases, a method may have to catch different
types of exceptions. Java supports multiple catch blocks.
Each catch block must specify a different type of exception: |
| |
try
{
// method calls go here
}
catch( SomeExceptionClass e )
{
// handle SomeExceptionClass exceptions here
}
catch( SomeOtherExceptionClass e )
{
// handle SomeOtherExceptionClass exceptions here
} |
| |
| When an exception is thrown in the try block, it is
caught by the first catch block of the appropriate type. |
| A method that ignores exceptions thrown by the method it calls. |
| |
import java.io.* ;
import java.lang.Exception ;
public class MultiThrow
{
public static void main( String[] args )
{
try
{
fool() ;
}
catch( Exception e )
{
System.out.println( "Caught exception " +
e.getMessage() ) ;
}
}
static void fool() throws Exception
{
bar() ;
}
static void bar() throws Exception
{
throw new Exception( "Who cares" ) ;
}
} |
|
| |
| In the example main() calls fool() which calls bar().
Because bar() throws an exception and doesn't catch it, fool() has
the opportunity to catch it. The fool() method has no catch
block, so it cannot catch the exception. In this case, the
exception propagates up the call stack to fool()'s caller, main(). |
| |
| A method that catches and rethrows an exception. |
| |
import java.io.* ;
import java.lang.Exception ;
public class MultiThrowA
{
public static void main( String[] args )
{
try
{
fool() ;
}
catch( Exception e )
{
System.out.println( "Caught exception " +
e.getMessage() ) ;
}
}
static void fool() throws Exception
{
try
{
bar() ;
}
catch( Exception e )
{
System.out.println( "Re throw exception -- " +
e.getMessage() ) ;
throw e ;
}
}
static void bar() throws Exception
{
throw new Exception( "Who cares" ) ;
}
} |
|
|
| |
| The fool() method calls bar(). The bar() method throws
an exception and fool() catches it. In the example, fool() simply
rethrows the exception, which is ultimately caught in the
application's main() method. In a real application, fool() could
do some processing and then rethrow the exception.
This arrangement allows both fool() and main() to handle the exception. |
| |
| |