O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

22.7. Handling Exceptions in a Custom Tag Class

Problem

You want your custom tag handler to deal with any exceptions thrown inside the tag.

Solution

Implement the TryCatchFinally interface in your tag handler.

Discussion

The tag extension API provides the TryCatchFinally interface, which you can implement in your tag handler class to write code dealing with any exceptions the tag handler might throw. If the class implements TryCatchFinally, it must include the methods doCatch( ) and doFinally( ). In doCatch( ), the code has access to any Throwable object thrown by doStartTag( ) or doEndTag( ), for instance. In doFinally( ), the code closes any resources the tag uses, such as a database connection.

In general, this interface allows the tag handler itself to catch and handle any exceptions that do not affect the output of the JSP enclosing the tag. Example 22-5 uses the same code as Example 22-1, but additional methods are added by implementing the TryCatchFinally interface.

Example 22-5. A logo tag handler that catches any exceptions

package com.jspservletcookbook;    

import javax.servlet.*;
import javax.servlet.http.*;import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/** This tag generates a thumbnail image using the HTML img tag, next to a text message.
The user specifies the content of the message and the Heading level (i.e., <H1>-<H6>) */

public class LogoTag extends BodyTagSupport implements TryCatchFinally{ private String heading = null; private String image =null; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required