Good exception handling policy for Java web application

I'm looking for a good exception handling policy for Java web application. First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
Then I found this Oracle page The Message-Driven Bean Class - The Java EE 6 Tutorial, which does just that. So now I'm confused. Is there a good page online for an exception handling policy for Java EE Web applications? I have a hard time finding one. I've read that you should not catch the Exception class. I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop. We have a loop which runs once a minute implemented using the Quartz framework. Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.

I'm looking for a good exception handling policy for Java web application.
If you have not done so I suggest you start by reviewing the several trails in The Java Tutorials.
Those trails cover both HOW to use exceptions and WHEN to use them.
This trail discusses  the 'controversy' you mention regarding 'Unchecked Exceptions'
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Unchecked Exceptions — The Controversy
Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Generally don't catch an exception unless you plan to HANDLE the exception. Logging, by itself is NOT handliing.
First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace(); 
That article, like many, has some good advice and some poor or even bad advice. You get what you pay for!
I've read that you should not catch the Exception class.
Ok - but all that does is indicate that a problem of some sort happened somewhere. Not very useful info. Java goes to a lot of trouble to provide specific exceptions for specific problems.
I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop.
If the exception is 'unknown' then maybe it NEEDS to 'stop all other customers from executing later on in the loop'.
That is EXACTLY why you don't want to do that. You need to identify which exceptions should NOT stop processing and which ones should.
Some 'unknown' exceptions can NOT be recovered and indicate a serious problem, perhaps with the JVM itself. You can NOT just blindly keep executing and ignore them without risking data corruption and/or the integrity of the entire system Java is running on.
Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.
No - not if you want a well-behaved system.
Don't catch exceptions unless you HANDLE/resolve them. There are times when it makes sense to log the exception (which does NOT handle it) and then raise it again so that it gets handled properly later. Yes - I know that is contrary to the advice given in that article but, IMHO, that article is wrong about that point.
If you have ever had to maintain/fix/support someone else's Java code you should already understand how difficult it can be to find WHERE a problem occurs and WHAT the exact problem is when exceptions are not handled properly.

Similar Messages

  • High thread context switching for java web application

    We have been load testing our java web application and observe high cpu usage with 50 users (which doesn't seem practical). The CPU shoots up above 80%. While profiling it with java flight recording (JFR) we see that the context switch rate is 8400 per second (as seen in the Hot threads tab on java mission control). Analyzing the hot threads in jfr, it seems the cpu usage is distributed across the application threads with each thread using less than 3% cpu.
    Increasing the user load to 100, 150 or 200 users we see the cpu shooting up above 90%, the throughput (transactions per second) remaining constant (as seen for 50 users load) while the response time crosses the acceptable threshold values (3 sec). Decreasing the user load to 20 users shows the cpu usage averages out to be above 55%. It certainly isn't true that the application threads are using up the cpu since our application is not a CPU bound application. The Hot Packages tab under Code tab group confirms this by showing that most of the time the application spends in is executing database queries.
    We use glassfish 3.1.2.2 as our application server where the max thread pool is configured to be of 100. Oracle Linux Server release 6.4 is our operating system with linux kernel version as 2.6.39-400.214.4.el6uek.x86_64. I tried executing linux commands namely "watch -n0.5 pidstat -w -I -p " and "watch -n.5 grep ctxt /proc//status" to see the voluntary and involuntary thread context switching at OS level but they don't give any results.
    Suspecting that high context switching could be causing the cpu to shoot up, do you have guidelines on what could be done to confirm that thread context switching is the cause of high cpu and what are there ways to tune the jvm or the application if that's the cause?
    Thanks!

    Kelum -
    We just saw this issue today for the first time. Have you been able to find a cause?
    We upgraded our 32bit Windows operating systems this weekend to use the /3GB flag. Since then, we have seen that our servers have ample heap space, but are dangerously low in PTE memory.
    But when we've been diagnosing the state of the server that produced this error (we run 2 nodes on 3 different computers; only 1 produced this error; the other 5 are working normally), everything looked fine. The server was reporting sufficient PTE availablility, plenty of heap space, and around 172 threads (we expect to be able to run many more than that).
    When we restarted the node, it came up fine and everything appeared to be working normally.
    So I'm looking for any clue as to the root cause, and what kind of resolution to explore. Any clues or pointers would be greatly appreciated.
    Paul Christmann

  • [ANN]REPORTMILL 5 BRINGS PDF AND FLASH TO JAVA WEB APPLICATIONS

    REPORTMILL 5 BRINGS PDF AND FLASH TO JAVA WEB APPLICATIONS
    Dallas, TX - February 25, 2002 - ReportMill Software, Inc. today announced the
    general availability of ReportMill 5 - the only developer tool in the world providing
    dynamic PDF and Flash web pages and reports for web applications. The new version
    is written entirely in Java and runs on all major platforms with support for all
    Java based web application servers, including those from BEA, IBM, Oracle, Sun
    and Apple.
    ReportMill rescues web developers from the crude look and feel that HTML-only
    solutions provide. By complimenting systems like Java Server Pages (JSP) from
    Sun, ReportMill brings a new level of professionalism and functionality to web
    applications.
    "Most web sites today offer much of their content in PDF and Flash, however, web
    applications are still limited to less-expressive HTML. Our customers deliver
    professionally formatted pages, such as invoices, catalogs, financial statements
    and itineraries in the paginated and printable Adobe PDF format. They offer content
    navigation that is interactive and portable in Macromedia Flash," says Jeff Martin,
    ReportMill CEO. "Only ReportMill seamlessly provides both with an integrated page
    layout application and an intuitive developer library."
    Availability and Pricing
    Available now. A fully functional evaluation version of the product is also available
    as a direct launch from your browser at http://reportmill.com/webstart.
    List pricing for ReportMill 5 starts at $495 (US) per developer and $4,995 (US)
    for a single processor deployment license. Volume pricing does apply. For specific
    pricing details, please see http://reportmill.com/pricing.html.
    About ReportMill Software, Inc.
    ReportMill Software, Inc. is the leader in web application "Object Reporting"
    and PDF and Flash content delivery for Java web applications. Founded in 1997,
    ReportMill has been the darling of the Apple WebObjects community, providing professional
    content solutions for dozens of fortune 500 corporations such as Merrill Lynch,
    Morgan Stanley, Fannie Mae, Verizon, WorldCom, NTT Communications, America Online,
    EDS, KPMG, AIG, Toyota and more. Now available to all web application servers,
    ReportMill will soon be a fixture in all web application development.
    Contact
    ReportMill Software, Inc.
    214.513.1636
    [email protected]

    REPORTMILL 5 BRINGS PDF AND FLASH TO JAVA WEB APPLICATIONS
    Dallas, TX - February 25, 2002 - ReportMill Software, Inc. today announced the
    general availability of ReportMill 5 - the only developer tool in the world providing
    dynamic PDF and Flash web pages and reports for web applications. The new version
    is written entirely in Java and runs on all major platforms with support for all
    Java based web application servers, including those from BEA, IBM, Oracle, Sun
    and Apple.
    ReportMill rescues web developers from the crude look and feel that HTML-only
    solutions provide. By complimenting systems like Java Server Pages (JSP) from
    Sun, ReportMill brings a new level of professionalism and functionality to web
    applications.
    "Most web sites today offer much of their content in PDF and Flash, however, web
    applications are still limited to less-expressive HTML. Our customers deliver
    professionally formatted pages, such as invoices, catalogs, financial statements
    and itineraries in the paginated and printable Adobe PDF format. They offer content
    navigation that is interactive and portable in Macromedia Flash," says Jeff Martin,
    ReportMill CEO. "Only ReportMill seamlessly provides both with an integrated page
    layout application and an intuitive developer library."
    Availability and Pricing
    Available now. A fully functional evaluation version of the product is also available
    as a direct launch from your browser at http://reportmill.com/webstart.
    List pricing for ReportMill 5 starts at $495 (US) per developer and $4,995 (US)
    for a single processor deployment license. Volume pricing does apply. For specific
    pricing details, please see http://reportmill.com/pricing.html.
    About ReportMill Software, Inc.
    ReportMill Software, Inc. is the leader in web application "Object Reporting"
    and PDF and Flash content delivery for Java web applications. Founded in 1997,
    ReportMill has been the darling of the Apple WebObjects community, providing professional
    content solutions for dozens of fortune 500 corporations such as Merrill Lynch,
    Morgan Stanley, Fannie Mae, Verizon, WorldCom, NTT Communications, America Online,
    EDS, KPMG, AIG, Toyota and more. Now available to all web application servers,
    ReportMill will soon be a fixture in all web application development.
    Contact
    ReportMill Software, Inc.
    214.513.1636
    [email protected]

  • Can't connect to Oracle XE instance from Java web application

    I'm a long-time Java developer but can't figure this out.
    I've been pouring over the forum for over a week and can't
    find the solution that will let me connect.
    Hardware: Intel/Vista.
    DB: Oracle Express 10G.
    Application: Java web application (Jakarta Struts)
    Application Server: Tomcat 5.5
    I copied the latest JDBC driver from OTN into my app server's "/LIB" directory.
    I get no driver errors. ("ojdbc14.JAR)"
    I can connect locally from my TOAD client, using SYSTEM/PASSWORD/XE.
    My listeners seem to be OK.
    Depending on which connection string I use from my Java application,
    I get one of two messages.
    "ORA-01017: invalid username/password; logon denied"
    OR
    "Io exception: The Network Adapter could not establish the connection"
    ------------ lsnrctl status ---------------------------------------------------
    Service "CLRExtProc" has 1 instance(s).
    Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
    Service "PLSExtProc" has 1 instance(s).
    Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
    Service "XEXDB" has 1 instance(s).
    Instance "xe", status READY, has 1 handler(s) for this service...
    Service "XE_XPT" has 1 instance(s).
    Instance "xe", status READY, has 1 handler(s) for this service...
    Service "xe" has 1 instance(s).
    Instance "xe", status READY, has 1 handler(s) for this service...
    The command completed successfully
    ------------ SOURCE CODE ------------------------------------------------------
    OracleDataSource ods = new OracleDataSource();
    ods.setURL(" jdbc:oracle:thin:@localhost");
    conn = ods.getConnection("system", "password");
    //ods.setURL("jdbc:oracle:thin:@rsosborn-PC:1521:XE");
    //conn = ods.getConnection("system", "password");
    String query = "select * from books;";
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(query);

    Using the code you supplied I was able to reproduce your errors. I've adjusted it accordingly and can connect to one of my 10.2 test databases.
    import java.sql.*;
    import oracle.jdbc.*;
    import oracle.jdbc.pool.*;
    class Conn {
      public static void main (String args []) throws SQLException
        Connection conn = null;       
        OracleDataSource ods = new OracleDataSource();
        // ods.setURL(" jdbc:oracle:thin:@localhost:1521:TEST");
        // conn = ods.getConnection("scott", "tiger");
        ods.setURL("jdbc:oracle:thin:@localhost:1521:TEST");
        conn = ods.getConnection("scott", "tiger");
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("select BANNER from SYS.V_$VERSION");
        while (rset.next())
            System.out.println (rset.getString(1));   // Print col 1
        stmt.close();
    }There are several different ways to configure OracleDataSources:
    http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/urls.htm#BEIDBFDF
    So, hopefully it's just a mismatch config.

  • Integrating a Java web application into the SAP NetWeaver Portal

    Hello experts,
    We have a requirement to integrate a Java based web application into the SAP NetWeaver Portal using iView/iFrame technology. The Java based web application is completely independent from the SAP environment but should be displayed as part of the SAP Portal environment. The other requirement is the main navigation menu for the Java based web application should be configured and provided in the SAP Portal.
    Any pointers on how exactly this can be done would be of great help.
    Also how can the SSO (Single-Sign-On) to the Java application be implemented so that the user can logon to the java application through the portal without providing the user credentials again.
    Thanks in advance.

    Hi,
    I think you can use URL iviews to integrate your java web application with EP. you have the option of doing SSO with the application as well.
    Have a look at the sap help material
    http://help.sap.com/saphelp_nw04/helpdata/en/f5/eb51730e6a11d7b84900047582c9f7/frameset.htm
    http://wiki.sdn.sap.com/wiki/display/BOBJ/CreateURLiviewintotheSAPEP+portal
    Regards,
    Ganesh N

  • Configuring the authentication scheme for a web application

    Hi all,
    We have a requirement to configure the authentication scheme for a web application where some set of users should access the application using basic LDAP (userid/password) authentication and some using digital certificate authentication.
    Since the deployment descriptor (web.xml) allows only one directive for auth-method in logic-config, we want to know if there is any other way to achieve this requirement. We are thinking of a custom login module approach. But we are not able to figure out how to configure the auth-method at runtime from the login servlet.
    Please let us know if there is any other approach to achieve this.
    I will be thankful if any body shares any specific solution to this issue.

    This forum is probably not the correct one to ask in. It's more related to the web container than Java Programming.
    Kaj

  • Front End (GUI) for Java Web Based Appl.

    Hi Gurus,
    I am new to Java. Can anybody tell me, what is the front end(GUI) used in Java web based applications? I was told that Swings/Applets are rarely used. Is there are a 3rd party took to design GUI for Java based applications?
    Chooti Baba

    sunilmp wrote:
    U mean to say, for JSP/Servlets, "Web based application" as well as "JSP/Servlet" usually implies that the client is a simple web browser.
    we cannot have swing as front end?You can use Swing inside an Applet inside a web application, but usually that's not needed, as you already have a client application that's quite powerful (the browser).

  • Upgrading BOE XI R2 Java Web Applications to use BOE XI 3.1

    Hello,
    Does anyone know where I can get documentation about how to update Java Web Applications using BOE XI R2 to BOE XI 3.1? I search the documentation online and I couldn't find any.
    I believe that it should be a matter of just updating the Java Archve (JAR) files and the helper files in the 'crystalreportviewers' folder. There should not be any changes to how I use the Enterprise SDK, RAS and Viewers SDK. If there are any, there should be very few. I just want to make sure of this.
    Thanks,
    R.C.

    Hi,
    Upgrading the Jar files and viewers directory ( crystalreportviewers12) should be sufficient. Please refer to 3.1 Java developer guide for ,pre information.
    Thanks
    Aasavari

  • Help on Sun Certified Developer for Java Web Services (CX-310-220) exam

    Hi,
    I am planing for Sun Certified Developer for Java Web Services (CX-310-220) certification. Can anyone provide me the links for resouces? can anyone provide me books/publications/author best preparation material to score good marks in exam? can anyone provide me the download resources available over internet?
    thanks in advance..!!!
    regards
    gaveesha

    yes, that's the only decent book covering most of the exam curiculum (but NOT all of it, check the exam specs versus the book content to know what you are missing).
    I'm working on the same material, and boy is it a lot...
    Dry, boring stuff most of it.

  • How can make java servlet sent soap message to other java web application

    hello,
    i want to make simple servlet send soap message to other java web application containing web service????
    for example
    web application " A " contain web service add two number
    java servlet " B " send soap message contain num1 and num2 to A to add them.
    how can do this????

    I tried that but my problem is that the code is so old. At least what I saw. I don't know how old is too old and I'm trying to do things "right." I saw code from 1998, but I don't know if that's still what you do. It might still work, but that doesn't mean it's correct. There's so much out there on Java that so old that half the time I'm not sure what to do because some other technology in J2EE or the latest Java SDK might have come up with a new way to do things. Thanks.

  • When we starting IR and ID, it will look for java web start platform? why?

    When we starting IR and ID, it will look for java web start platform? why?

    hi praveen,
    Java web start is platform to launch the java application.
    All the file from the central server are copied to the local machine
    check the below blog
    Java Web Start                                   
    Have some more Fun.......                         
    regards
    kummari

  • I am planing for Sun Certified Developer for Java Web Services (CX-310-220)

    Hi,
    I am planing for Sun Certified Developer for Java Web Services (CX-310-220) certification. Can anyone please provide me the resources for preparation?
    Can anyone suggest me which books/author/publications best helps me to get good results in exam? Any books/author/publications available over internet to download and prepare?
    regards
    gaveesha

    yes, that's the only decent book covering most of the exam curiculum (but NOT all of it, check the exam specs versus the book content to know what you are missing).
    I'm working on the same material, and boy is it a lot...
    Dry, boring stuff most of it.

  • Configure Log File for each web application deployed in weblogic server usi

    Hi All,
    How do I configure Log4J to log separately for each web application? i.e. Assuming, I have a web application "AWeb" and a web application "BWeb". I need a log file to be created for AWeb Separately and BWeb Separately. i.e. All the log information for "AWeb" web application will be stored in AWeb.log and all the "BWeb" web application will be stored in BWeb.log
    Do you have any sample code and configuration details for the above-mentioned requirement?
    Thanks in Advance,
    C R Baradwaj

    You do not need to do anything strange, just use log4j the usual way with the exception that you do not need to init log4j (this is not necesary when using a log4j.xml.)
    A minimal sample of a log4j.xml is
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.SimpleLayout"/>
    </appender>
    <root>
    <priority value ="debug" />
    <appender-ref ref="ConsoleAppender"/>
    </root>
    </log4j:configuration>
    You just have to be sure that you have different log4j.xml in your classpath for different web applications.
    Regards,
    LG

  • Is there a forum for Java GUI Application Design?

    Hi all,
    I've used this forum a lot and found a lot of help on it for Swing usage specifics. However, whenever I ask a question about broader design or architecture of a full Swing app I get little or no response. Sadly I'm no stranger to "view 50, replies 0" :o(
    Either I'm asking stupid questions or I'm asking the in the wrong forum - does anyone know of a good place to ask about design/best practices for Java, GUI applications? I've seen some of the "programmer"/"developer" groups on Google Groups.
    Many thanks.
    Yours, hoping for at least one reply,
    Chris

    You're right, I typed that wrong. The method signature should be addDataChangeListener(DataChangeListener lis, DataChangeType type)
    When a component registers itself as a change listener, say it wants to know whenever an object of type Foo is changed, it calls DataChangeType.addDataChangeListener(this, DataChangeType.FOO). (the Enum elements coorespond to the objects we want to listen for) Then it implements the dataChanged(DataChangeType type, Object obj) method that will be called by the controller when objects of type Foo are changed. (obviously this is an interface) Whenever a component updates an object of type Foo, it calls DataChangeControl.dataChanged(DataChangeType.FOO, theFooObject), and then the controller will notify all listeners who are interested in Foo objects changing.
    The DataChangeControl maintains a hashmap of <DataChangeType, List < DataChangeListener> >. So when a new listener is added, it checks the type to see if a list is already keyed to that object type in the hashmap. If so it adds the listener to that list, if not it creates a new list in the hashmap with the type as the key. That way when an object is changed, it notifies only those listeners who are registered to listen to that type of object being changed. Hopefully that makes sense.

  • Can I setup a Java Web Application on Business Catalyst?

    I wanted to know if I can upload a Java Web Application on to Business Catalyst.  What kind of features are supported, etc, for Java Developers, ex. Spring, Jar Integration, etc.
    Thank You.

    Hi there,
    No you cant. You can not install any server side programming on BC. It is a closed system. it is also .NET based.

Maybe you are looking for

  • Itunes and maximum number of files

    having finally finished creating an mp3 library of all my music, I have an awful lot of MP3 files - like approximately 1gb that is currently sitting on an external hard drive Now, I have an imac 20" with a 1TB drive in it - and i got to thinking - ca

  • Emacs opening files and lisp

    I have been playing around with emacs for the mac. I usually use it from the command line, but I would also like to use it from the GUI so I can get rid of the text editor and word. I have set it so that text files open emacs, but it opens emacs with

  • Converting a .PSD into an .AI to become a vector in After Effects

    I'm trying to Extrude my logo in After Effects CS6 to appear 3D. My understanding is I need to import an Illustrator file (.AI) in order to "Creat Shapes from Vector Layer". I'm having trouble opening a .PSD and then saving it as an .AI. The file is

  • Imac Ram replacement in aluminum duo core now with three beeps!!

    Ok, I had a 2 gig stick in a bought a 1 gig stick to put in the other slot. As it turns out both sticks are made by the same manufacturer (Hynix) and both are pc2-5300s-555-12. I put in the 1 gig and got the three beeps with both sticks in. I took ou

  • BCUser Login Issue-

    Hi, I am using NW2004s ABAP trial edition. When I tried using BCUSER (password : minisap)but the system says 'Password logon no longer possible - too many failed attempts'. Please help me out..I don't know where am I making a mistake. FYI: I couldn't