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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s two cases I can potentially think of – the first similar case I can think of is when implementing
finalize(), you have to throwThrowable:…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:
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 (IllegalArgumentExceptionfor 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
RuntimeExceptionisn’t so bad – it’s still very unspecific but at least doesn’t force the caller to catch everything explicitly.