Link to home
Start Free TrialLog in
Avatar of changcy77
changcy77

asked on

where to throw and where to catch the Exception in a web application?

Dear experts,

I am writing a web app which mainly used JSP. I just wonder where should we throw the or catch exceptions? Since it is a web app, I don't think it would make much sense to catch the exception before it reaches the browser. I wonder what would be the standard way to handle this? Should we also use "log" to log the error from server side? What is the best way to implement this?

Thanks.
Avatar of girionis
girionis
Flag of Greece image

 Exceptions to web applications do not differ from exceptions to standard Java applications. You still need to catch a FileNotFoundException for instance if you are doing file processing on the server side. If you do not catch an exception you make the debugging more difficult and the flow of your web app ambiguous.

  As for logging I'd say it depends. If the project is very big then I strongly suggest loging since you can always go through the log files for usefl information. You might also want to take a look at log4j from the apache project: http://jakarta.apache.org/log4j/docs/index.html
Avatar of changcy77
changcy77

ASKER

Thanks.

Could you please explain a little more about what you meant by "the flow of your web app ambiguous."?

So, should not the user be informed if something goes wrong at the server side?

Thanks.
You will still catch the exception in jsp the same way as you do in java as girionis mentioned, like this:
<%
  try
  {
    // Some java code here
    ....
  }
  catch (Exception e)
  {
    e.printStackTrace ();
  }
%>

But JSPs has one more directive to handle unhandled exceptions.
On the top, put this in your jsp :

<%@ page errorPage="error.jsp"%>

What does this directory means is that error.jsp is an error page, and any exception occuring on the current jsp which is not handled, will redirect the jsp to error.jsp page where the exception will be available to error.jsp as the variable by the name 'exception'.

So your error.jsp will look something like this :

<%@ page isErrorPage="true" %>
<%@ page import="java.io.*" %>
 Exception Stacktrace:<br>
    <% exception.printStackTrace();

        StringWriter sr = new StringWriter ();
        exception.printStackTrace (new PrintWriter (sr));
        String stkTrace = sr.toString ();
    %>
    <%= SIPSUtils.replace (stkTrace, "\n", "<br>") %>


Hope that helps
Thanks
Amit
 By saying that you make the flow of your web app ambiguous I mean that you are never sure what the flow is. Imagine if an exception occurs and you do not catch it, you can never be sure if the flow went through the right statement or not.

  Besides as amit_chauhan pointed out JSP pages have the advantage to redirect the error output to another page so the user is informed about the error.

> So, should not the user be informed if something goes wrong at the server side?

  This depends heavily on the kind of exception. If you follow the EJB model you will see that only application level exceptions need to be thrown back to the user. By application level exeptions I mean exceptions that concern the web application and the user (for example you might define your own exception about insufficient funds in a banking web application) needs to know about it. System level exceptions (such as database or network problems) do not usually need to be thrown back to the client, but you could if you wanted.
Thanks to both. It's very helpful.

But, Amit that does this do?
  <%= SIPSUtils.replace (stkTrace, "\n", "<br>") %>
Oh :) am sorry, I cut-pasted the code from my application, which has a utility method to search and replace a string. You can ignore that. Basically as am displaying this on web page, I have to replace new line characters with <br> tag.
Just print the stacktrace :
Replace that code with this :
<%=stkTrace%>

Thanks
Amit

You should be catching exceptions if you need to perform some action to handle them.
And set up specific error pages in web.xml to handle uncaught exceptions.

That could be a good idea too if you want to handle specific exceptions differently, or forwarding them to specific pages based on the exception.

But as Objects mentioned, you should be catching exceptions. As a good practice, have your java code in jsp on the top, before html begins, and the code should be within try-catch block to catch all exceptions. You can rethrow the exception after logging it (or performing some action), which will redirect the page to error.jsp page if you have included the errorPage directive. error.jsp chould be primarily used when some unhandled exception occurred while printing html.

Thanks
Amit
JSP.... ?? I think the errorPage option is the best, as amit_chauhan has already suggested.

Mayank.
> I think the errorPage option is the best

But there are still times where an exception will need to be caught and handled. Just displaying an error page is not always sufficient.
Agreed, buddy.... I think there are enough comments here to help him with that//

Cheers,

Mayank.

From "asker" point of view, comments are always welcomed and never too much. I thank everyone's input.

I will think about it and decide how to give the points.

Dear experts,

This brought up another question...

I also wondering if we are not at the console, but running a remote server, how could the catch exception help us debugging? I mean we can't see the "System.out.println", right? What is the common practice people use for web debugging? Should we write to a file instead?

Thanks.
Write to a file or send an error email.
Usually you can write to System.err and in most production system this is redirected to a file. check how its organised in your prod system. If its still stdout, then write to a file urself.

Thanks
Amit
Thanks very much, Amit.

I am going to raise the points to 50 since it is getting more challenging...

Another question is then how do you handle different type of exceptions? Does it depend on the business rule?

But, just generally speaking, how does people handle each of these? Is it acceptable to just display an error page to the user or it should always ends with nice messages?

1. If database connection has problem
2. database query return no result
3. database insert failed
4. User input error ( showsing remind meesage to user to ask for correct input)
ASKER CERTIFIED SOLUTION
Avatar of amit_chauhan
amit_chauhan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial


Thanks.

Another question(sorry) is what option should we choose when we catch exceptions? I have used e.getMessage(), e.toString(), printStackTracke() ...I can't really see the benefit of over the others, any rule for this?
e.getMessage (), e.toString () and e.printStackTrace () gives error details in increasing order of detail level.

e.getMessage () returns just the error message, like 'File not found at c:\abc\x.txt" etc.

e.toString () returns the message as well as the exception name. e.g java.io.FileNotFoundException : 'File not found at c:\abc\x.txt".

e.printStackTrace () gives the whole exception stacktrace starting from the String returned by toString () method and then the trace from which class/method the error occurred to the one that initiated the call.
e.g.

java.io.FileNotFoundException : 'File not found at c:\abc\x.txt".
at com.abc.xyz.class1.java (line 23)
at com.abc.xyz.class2.java (line 123)
at com.abc.xyz.class3.java (line 43)


Hope that helps
Thanks
Amit