Discussions

EJB programming & troubleshooting: Is this a good way to handle Exceptions?

  1. Is this a good way to handle Exceptions? (2 messages)

    Hi pls consider following in a stateless session bean public method.

    ...
    try{
      ...
      ...
      String xml = null;
      try{
         xml = parseXML(stream);
      } catch(IllegalCharacterException e) {
         log.error("Error-illegal char in input" + e.getMessage());
         throw e;
      }
      try{
          int Id = insertInDB(xml);
      }catch(DAOException e){
         log.error("DB Error" + e.getMessage());
         throw e;
      }
     }catch(Exception e) {
       sessionContext.setRollbackOnly();
       throw new EJBException(e);
     }
     ....
     ....
    questions
    1) Is it good practice to put a global try catch to catch any exception happend during execution?
    2) Is it good practice to throw EJBException.
  2. Is this a good way to handle Exceptions?[ Go to top ]

    Yes It is good & recommended practice to have a global exceptions in this case. Throwing an exception is a good practice, but handling them with care takes a lot to it as well.

        try {
          ....
          ....
          String xml = null;
          xml = parseXML(stream);
          int Id = insertInDB(xml);
          ....
          ....
        }
        catch (IllegalCharacterException e) {
          log.error("Error-illegal char in input" + e.getMessage());
          throw e;
        }
        catch (DAOException e) {
          log.error("DB Error" + e.getMessage());
          throw e;
        }
        catch (Exception e) {
          sessionContext.setRollbackOnly();
          throw new EJBException(e);
        }
  3. Is this a good way to handle Exceptions?[ Go to top ]

    In general, I don't see the point of logging, then throwing the exception again. Catching it solely to log it isn't a good enough reason to catch it ... you end up catching it, logging it, throwing it, catching it again higher up, logging it, throwing it, etc. The same stack trace ends up again and again in your logs, and really doesn't do anything other than complicate things.

    In general, don't catch unless you're going to do something about it. For instance, you might rethrow a checked exception as an unchecked exception. Or you might be able to recover in some way. But unless you can, life is cleaner and better to just assume that someone above you is going to deal with it, one way or another.

    The exception to this, of course, is to catch things at the entry point of a module so it can be logged. For instance I always catch Throwable in a servlet service() method, so that I can at least log anything that makes it that high up.