mrtasln
mrtasln

Reputation: 41

Try/Catch in Constructor

public class MyClass{

    private String url;
    private static InputSource is;

    public MyClass(String link){
        this.url=link;
        try {
            is = new InputSource();
            is.setEncoding("UTF-8");
            is.setByteStream(new URL(url).openStream());
        } catch (Exception e) {
            Logger.debug(e);
        }
    }
}

I have three methods and I'am using InputSource in all methods. So I want to create one InputSource with constructor and use it in all methods. How can I do it? Does anyone have any idea? Should I use try-cath block in constructor?

Upvotes: 1

Views: 4574

Answers (3)

Luis Sieira
Luis Sieira

Reputation: 31612

If the InputSource constructor can throw an exception, I don't see why your constructor can't. You have two options, doing what you are doing, but avoiding using a pokemon exception handler, and handling it properly; or, for better error handling, you should make your constructor throw a custom exception.

EDIT In case the link breaks, a pokemon exception handler is the one you use when you just Gotta Catch 'Em All.

try {
  // do something
} catch {
  // catch em all
}

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140564

Using try/catch in the constructor is fine, but I wouldn't swallow the exception like that.

You will potentially end up with a partially-initialized instance that will fail later when you try to use it.

E.g. in this case, you might end up with is being null. This might be fine for some operations on that class, but it might be dereferenced in some obscure code path, leading to a very hard-to-debug issue, since the exception in the constructor happened much earlier.

A more subtle (read: far worse) bug would be if setting the encoding failed, leaving your input source not configured to read UTF-8 text correctly. This would then give you back garbage, potentially, but you wouldn't know as it would be "valid" garbage. (Actually, this is unlikely to happen, as UTF-8 encoding has to be supported by specification. However, as a general strategy, silent failures should be avoided).

I would propagate the exception somehow, either by simply declaring throws on the constructor, or rethrow the exception as an unchecked exception (if appropriate).

Additionally, I would not catch/declare throws Exception: this masks the fact that specific exception types can be thrown, when those exceptions would need to be handled in a specific way (e.g. InterruptedException).

Upvotes: 8

Daniel Jipa
Daniel Jipa

Reputation: 888

Yes, you can use try-catch as you can use it in regular methods.

Upvotes: -1

Related Questions