Software Development, Linux, and Windows

Notes on Software Development, Linux, and Windows

Handling Multiple Exceptions in one catch block

Overview

Java 1.7 added support to handle more than one Exception in a single catch block.

Example:

This is a nice feature, and here is an example that demonstrates this and how to extract the name of the Exception class being thrown for logging:


package com.petersarazin.exception;

import java.io.IOException;

import org.junit.Test;

public class ExceptionHandling_Test {

@Test
public void testJava7MultipleExceptionHandling()
{
try
{
doSomeIoStuff();
throw new UnsupportedOperationException( “No can do…” );

}
catch( IOException | IllegalArgumentException | UnsupportedOperationException exception )
{
System.err.println( exception.getClass().getName() + ” caught in testJava7MultipleExceptionHandling(): ” + exception.getMessage() );
}
}

private void doSomeIoStuff() throws IOException
{
// throw new IOException( “Can’t get there from here…” );
}

}

Here is an example output message that is logged from this code:


java.lang.UnsupportedOperationException caught in testJava7MultipleExceptionHandling(): No can do...