Question

I'm making some JSP tag. I pass a type parameter to the tag.

The code look like this:

<%@ attribute name="type" require="true" %>
<c:choose>
    <c:when test="${type eq 'even'}">
        <c:set var="remainder" value="0" />
    </c:when>
    <c:when test="${type eq 'odd'}">
        <c:set var="remainder" value="1" />
    </c:when>
    <c:otherwise>
        <%-- Want to throw exception!! --%>
    </c:otherwise>
</c:choose>

I want to throw an exception if I pass a wrong value. When I searched about this subject I just found this. Can't I throw a normal exception in JSTL?

Was it helpful?

Solution

Just throw to notice the problem immediately

Who would "notice" ? That exception can only be caught by the container and it will result in some "500 Internal Server Error" page (or some custom error page you define).

If that's what you really want, you can define a custom tag that will just perform "throw new WhateverException()", and then make use of your custom taglib like: <mytaglib:reportError/>, as the standard core taglib did not consider throwing an exception would ever be desirable for anyone.

OTHER TIPS

I have decided to revive and edit a deleted answer which looked partially correct.

You can throw an exception by adding it in a scriptlet like so:

<c:choose>
    <c:when test="${type eq 'even'}">
        <c:set var="remainder" value="0" />
    </c:when>
    <c:when test="${type eq 'odd'}">
        <c:set var="remainder" value="1" />
    </c:when>
    <c:otherwise>
        <% if (true) throw new Exception("Wrong type"); %>
    </c:otherwise>
</c:choose>

However, your jsps are supposed to be part of your "view" layer so you should really try to keep your logic (including throwing the exception) in your servlets.

Note the if (true) statement. It is a trick becase the compiler will complain about "unreachable code" if you just drop the exception scriptlet into your code.

I would just use a custom EL function or tag which systematically throws an exception, or displays a big red div with the error message, or both

${myFn:illegalState("the type must be odd or even but it is " ${type})}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top