pgsandstrom
pgsandstrom

Reputation: 14399

controlling if exceptions are swallowed by a static boolean

So we are a few guys developing this product that is communicating with a really unstable server. It often returns very strange and corrupt data. During testing we want the resulting crashes to be loud, so we discover them. But every other day we need to demonstrate our product for a potential customer. To the customer the errors will go undiscovered if we just swallow them. I am thinking about implementing something like this around all server communication to quickly switch between swallowing exceptions and crashing:

try {
    apiCall();
} catch (Exception e) {
    if(!SWALLOW_EXCEPTION) {
        throw e;
    }
}

Is this an awesome idea, or can it be done in a better way?

Upvotes: 1

Views: 177

Answers (4)

Chris Dennett
Chris Dennett

Reputation: 22721

You could use an 'uncaught exception handler' instead. Check out the code at http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/ and http://www.javapractices.com/topic/TopicAction.do?Id=229. You can also write your handler to put the exceptions into a logger.

Upvotes: 0

Yishai
Yishai

Reputation: 91871

Did you intend your code to do this?

   try {
      apiCall();
    } catch (Exception e) {
      if(!SWALLOW_EXCEPTION) {
         throw e;
      } else {
         e.printStackTrace();
      } 
    }

If so, if this is the only place that this API is called, it seems ok to me, as long as you realize you will need to recompile for the change to take effect. You could abuse a logging framework to get that done without a recompile like this:

  if (logger.isInfoEnabled()) {
       throw e;
  } else {
       logger.error(e.getMessage(), e);
  }

But I think most people looking at such a piece of code would be very taken aback. If you want to avoid the recompile, just use a System property:

 if (Boolean.getBoolean("development")) {
       throw e;
 } else {
       e.printStackTrace();//you should really use a logging framework anyway and not this.
 }

Upvotes: 0

Chris Dail
Chris Dail

Reputation: 26029

I would recommend using a Logger like SLF4J, java.util.logging or Log4j. Any log messages that are 'debugging' but you still want tracked you can put to the DEBUG, INFO or WARN levels based on their severities. Real errors you can save for the 'Error' level.

When you do demos to customers, set your log level to Error so they don't see everything. When you are running normally though, set it to a level to capture the logging level you need.

Swallowing exceptions is never a good practice. By using a logger, you can hide them if it is giving you too much detail. You can always get access to them if you need without recompiling.

Upvotes: 6

David Soroko
David Soroko

Reputation: 9086

This is not pretty. How about implementing a top level (whatever that means in your context) error handler[s] that does that?

Upvotes: 2

Related Questions