Bad practice to have try / catch in constructor? [closed]

Posted on

Problem

I have a constructor which sets a member variable. The setting of this variable throws an exception. Should I be throwing the exception in the contructor or enclosing the try/catch like below. Is below snippet an example of code smell ?

private NewManager newManager;

    public Save(final TheManager manager, final String str) {
        this.manager = manager;

        try {
            this.newManager = manager.getManager(str);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

Solution

Catching an exception and just printing stack trace and proceeding like nothing happened is certainly Very Bad. What if no one is watching the standard error stream (where e.printStackTrace() dumps its output)? In your case, you’ll probably end up with NullPointerException later on, since newManager is not set. It could be one second from now, or one year from now, depending on when someone is trying to use newManager. You want to fail fast instead.

There’s nothing wrong in throwing exceptions from constructors. Just make sure that, wherever you catch it, you handle it appropriately.

Catching an exception should be done for one of two reasons.

  1. You want to log it before rethowing.
  2. You know how to handle the exception.

If you don’t know how to deal with an exception, catching it puts you into an unstable situation. You want to fail as quickly as possible for several reasons.

Let me be clear: this does not mean you have to “fix” the exception, it means you know what to do to allow the application to continue to operate appropriately. If you don’t know the consequences of the application continuing after an exception, then do not catch it, you’re just setting yourself up for further problems.

But if you can continue with reduced functionality or otherwise deal with the situation in an appropriate manner, then you should catch the exception and continue.

Leave a Reply

Your email address will not be published. Required fields are marked *