There are some places, where it is recommended to catch an exception, and to wrap it into a parameterized exception with its own message text.
The first is, if the exception is a checked one, and you don't want to specify it in the throws clause of your own method. Then the compiler forces you to catch it. In the catch branch you shoud usually wrap it.
The other is, even with an unchecked exception, if you want to add abstraction-specific diagnostic parameters, or a message text.
We present here as an example the code for opening a serial port
by means of javax.comm
, as was more detailedly
motivated in the german text Konzepte.pdf
.
package x; import multex.Exc; import multex.Failure; import static multex.MultexUtil.create; class SerialPort { ... /**Opens the serial port with the given name * and the other communication parameters.*/ public void open( String portName, int baudRate, int databits, int stopbits, int parity ) throws NameExc, OpenFailure { //1. Checking for business rule violations: if(!portName.startsWith("COM")){ throw create(NameExc.class, portName); } //2. Performing modifications: try { this.portName = portName; final javax.comm.CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName); //NoSuchPortException sp = (javax.comm.SerialPort)portId.open(null,0); //PortInUseException sp.setSerialPortParams( baudRate, databits, stopbits, parity ); //UnsupportedCommOperationException os = sp.getOutputStream(); //IOException is = sp.getInputStream(); //IOException } catch (Exception e) { ... //free resources //wrap exception and parameterize: throw create(OpenFailure.class, e, portName, baudRate, databits, stopbits, parity ); } //catch } //open /**The serial port name {0} is not allowed.*/ public static final class NameExc extends Exc {} /**Cannot open the serial port "{0}" with communication parameters portName * ={1}, baudRate={2}, databits={3}, stopbits={4}, parity={5} */ public static final class OpenFailure extends Failure {} } //SerialPort
Here we have the typical case, that the whole
modification part of the method body is surrounded by a
try-block, in whose catch-branch we
catch any Exception
and propagate it by throwing
a Failure
encapsulating the original exception
aside with diagnostic parameters. The caught exceptions include the
checked exceptions NoSuchPortException
,
PortInUseException
,
UnsupportedCommOperationException
, and
IOException
, where commented and any other
subclass of java.lang.RuntimeException
. You
always have to pass the causing exception to the first parameter of
MultexUtil.create
after the failure's
class.