JMS exception handling
Any run time errors in a JMS application results in a thrown javax.jms.JMSException. The JMSException class is the root class of all JMS API exceptions.
A JMSException contains the following information:
- A provider-specific string describing the error
- A provider-specific string error code
- A reference to another exception
The JMSException is usually caused by another exception being thrown in the underlying JMS provider. The JMSException class allows JMS client applications to access the initial exception using the getLinkedException method. The linked exception can then be used to determine the root cause of the problem in the JMS provider.
The implementation of JMSException does not include the embedded exception in the output of its toString method. Therefore, it is necessary to check explicitly for an embedded exception and print it out...
try { // Code which may throw a JMSException } catch (JMSException exception) { System.err.println("Exception caught: " + exception); Exception linkedException = exception.getLinkedException(); if (linkedException != null) { System.err.println("Linked exception: " + linkedException); } }However, when using a message listener to receive messages asynchronously, the application code cannot catch exceptions raised by failures to receive messages. This is because the application code does not make explicit calls to the receive methods on the message consumer.
The JMS API provides the javax.jms.ExceptionListener interface to solve this problem. An exception listener allows a client to be notified of a problem asynchronously. The JMS client must register an object that implements this interface with the connection using the setExceptionListener method. With an exception listener instance registered, the JMS provider invokes its onException method to notify it that a problem has occurred.
The javax.jms.ExceptionListener interface...
package javax.jms; public interface ExceptionListener { public void onException(JMSException exception); }A simple class that implements the javax.jms.ExceptionListener interface...
package com.ibm.itso.jms; import javax.jms.ExceptionListener; import javax.jms.JMSException; public class SimpleExceptionListener implements ExceptionListener { public void onException(JMSException exception) { System.err.println("Exception caught: " + exception); Exception linkedException = exception.getLinkedException(); if (linkedException != null) { System.err.println("Linked exception: " + linkedException); } } }