Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: What are the reasons for throwing Exception rather than a specific exception? [closed]

Are there reasons why you would want to do this:

void foo() throws Exception
{
    // Do something potentially exceptional
}

Rather than throwing an existing or custom exception?

like image 784
bn. Avatar asked Nov 30 '22 23:11

bn.


2 Answers

I wouldn't do it. It provides the minimum of information about what happened.

I think the current best practice would be to prefer unchecked exceptions (this is the C# way). The foo() method would catch checked exceptions and wrap them in a RuntimeException.

I'd either spell out the exceptions, wrap them in a more business specific custom exception, or wrap a RuntimeException.

like image 35
duffymo Avatar answered Jan 12 '23 00:01

duffymo


There's two cases I can potentially think of - the first similar case I can think of is when implementing finalize(), you have to throw Throwable:

@Override
protected void finalize() throws Throwable {
    super.finalize();
}

...though bear in mind some argue that using finalize should be discouraged in itself.

The potential second case is when using a (badly written) library whose method(s) may throw an Exception, in which case if you don't want to deal with it in that particular method your only option is to throw it up the stack.

Personally though, if that were me I'd most likely wrap it up in a RuntimeException then and there:

public void doSomething() {
    try {
        int x = libraryThing.badMethod(); //Library method that throws "Exception"
    }
    catch(Exception ex) {
        throw new RuntimeException("Couldn't do something", ex);
    }
}

The second argument to RuntimeException's constructor is important in this case though, since if it is thrown that will preserve the original exception on the stack trace as ("Caused by: x"). Of course, if you can find a more specific subclass of RuntimeException that you can guarantee is relevant in that context (IllegalArgumentException for instance) then using that would be better.

In terms of normal code however, nope - I'd argue it's nearly always an anti-pattern (and usually one just caused through laziness!)

As a side point, throwing a RuntimeException isn't so bad - it's still very unspecific but at least doesn't force the caller to catch everything explicitly.

like image 61
Michael Berry Avatar answered Jan 11 '23 23:01

Michael Berry