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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With