Extending Throwable in Java
Solution 1
I'd say that it is a really bad idea. A lot of code is implemented on the assumption that if you catch Error
and Exception
you have caught all possible exceptions. And most tutorials and textbooks will tell you the same thing. By creating a direct subclass of Throwable
you are potentially creating all sorts of maintenance and interoperability problems.
I can think of no good reason to extend Throwable
. Extend Exception
or RuntimeException
instead.
EDIT - In response to the OP's proposed scenario #1.
Exceptions are a very expensive way of dealing with "normal" flow control. In some cases, we are talking thousands of extra instructions executed to create, throw and catch an exception. If you are going to ignore accepted wisdom and use exceptions for non-exceptional flow control, use an Exception
subtype. Trying to pretend something is an "event" not an "exception" by declaring is as a subtype of Throwable
is not going to achieve anything.
However, it is a mistake to conflate an exception with an error, mistake, wrong, whatever. And there is nothing wrong with representing an "exceptional event that is not an error, mistake, wrong, or whatever" using a subclass of Exception
. The key is that the event should be exceptional; i.e. out of the ordinary, happening very infrequently, ...
In summary, a FlyingPig
may not be an error, but that is no reason not to declare it as a subtype of Exception
.
Solution 2
Is this technique of (ab)using exception valid? (Is there a name for it?)
In my opinion, it's not a good idea:
- It violates the principle of least astonishment, it makes the code harder to read, especially if there is nothing exception-al about it.
- Throwing exception is a very expensive operation in Java (might not be a problem here though).
Exception should just not be used for flow control. If I had to name this technique, I would call it a code smell or an anti pattern.
See also:
If valid, should
FlyingPig
extendsThrowable
, or isException
just fine? (even though there's nothing exceptional about its circumstances?)
There might be situations where you want to catch Throwable
to not only catch Exception
but also Error
but it's rare, people usually don't catch Throwable
. But I fail at finding a situation where you'd like to throw a subclass of Throwable
.
And I also think that extending Throwable
does not make things look less "exception-al", they make it look worse - which totally defeats the intention.
So to conclude, if you really want to throw something, throw a subclass of Exception
.
See also:
Solution 3
Here is a blog post from John Rose, a HotSpot architect:
http://blogs.oracle.com/jrose/entry/longjumps_considered_inexpensive
It is about "abusing" exceptions for flow control. Slightly different use case, but.. In short, it works really well - if you preallocate/clone your exceptions to prevent stack traces being created.
I think that this technique is justifiable if "hidden" from clients. IE, your FlyingPig should never be able to leave your library (all public methods should transitively guarantee not to throw it). One way to guarantee this would be to make it a checked Exception.
I think the only justification for extending Throwable is because you want to allow people to pass in callbacks that have catch(Exception e) clauses , and you wish your result to be ignored by them. I can just about buy that...
Solution 4
The org.junit.Test
annotation includes the None
class which extends Throwable
and is used as the default value for the expected
annotation parameter.
Solution 5
If you can justify what sets a FlyingPig apart from both Error and Exception, such that it is not suitable as a subclass of either, then there's nothing fundamentally wrong with creating it.
The biggest problem I can think of is in the pragmatic world, sometimes there are justifiable reasons to catch java.lang.Exception. Your new type of throwable is going to fly right past try-catch blocks that had every reasonable expectation of suppressing (or logging, wrapping, whatever) every possible non-fatal problem.
On the flipside if you're doing maintenance on an old system that is unjustifiably suppressing java.lang.Exception, you could cheat around it. (Assuming the sincere appeal for time to actually fix it properly is denied).
polygenelubricants
I mostly contributed in [java] and [regex] from February to August of 2010. I work for Palantir Technologies now, so I may not have much time on stackoverflow as I did then. We're currently hiring; you can e-mail me for a referral. A few habits I've developed on the site: I will no longer cast a downvote. It will stay at 54 forever. I don't like to engage in dramas on stackoverflow. If you really need to discuss politics and other non-technical issues with me, bring it to meta. I delete my comments once they've become obsolete I try to revise my answers periodically, so I prefer that you leave comments and feedbacks instead of editing my answers directly.
Updated on June 11, 2022Comments
-
polygenelubricants almost 2 years
Java lets you create an entirely new subtype of
Throwable
, e.g:public class FlyingPig extends Throwable { ... }
Now, very rarely, I may do something like this:
throw new FlyingPig("Oink!");
and of course elsewhere:
try { ... } catch (FlyingPig porky) { ... }
My questions are:
- Is this a bad idea? And if so, why?
- What could've been done to prevent this subtyping if it is a bad idea?
- Since it's not preventable (as far as I know), what catastrophies could result?
- If this isn't such a bad idea, why not?
- How can you make something useful out of the fact that you can
extends Throwable
?
- How can you make something useful out of the fact that you can
Proposed scenario #1
A scenario where I was really tempted to do something like this has the following properties:
- The "event" is something that will happen eventually. It is expected. It most definitely is not an
Error
, and there's nothingException
-al about when it occurs.- Because it is expected, there will be a
catch
waiting for it. It will not "slip" past anything. It will not "escape" from any attempt tocatch
generalException
and/orError
.
- Because it is expected, there will be a
- The "event" happens extremely rarely.
- When it happens, usually there's a deep stack trace.
So perhaps it's clear now what I'm trying to say:
FlyingPig
is the result of an exhaustive recursive search.The object to be searched exists: it's only a matter of finding it in the big sea that is the search space. The search process will be a long one, so the relatively expensive cost of exception handling is negligible. In fact, the traditional control flow construct alternative of using a
boolean isFound
flag may be more expensive, because it has to be checked continuously throughout the search process, most likely at every level of the recursion. This check will fail 99.99% of the time, but it's absolutely necessary to propagate the termination condition. In a way, while effective, the check is inefficient!By simply
throw
-ing aFlyingPig
when the sought object is found, you don't have to clutter the code with the management of theboolean isFound
flag. Not only is the code cleaner in that regard, but it may run faster due to this omission.So to summarize, the choice is between these two:
- Traditional control-flow approach
- Use a
boolean isFound
, checked continuously - 99.99% of the time, the check is a "waste", because it'd still be
false
- When it eventually becomes
true
, you stop recursing and you have to make sure that you can properly unwind to the initial call.
- Use a
FlyingPig
approach- Don't bother with any
boolean isFound
. - If found, just
throw new FlyingPig()
; it's expected, so there will be acatch
for it. - No management of
boolean
flag, no wasted check if you need to keep going, no bookkeeping to manually unwind the recursion, etc.
- Don't bother with any
Questions:
- Is this technique of (ab)using exception valid? (Is there a name for it?)
- If valid, should
FlyingPig extends Throwable
, or isException
just fine? (even though there's nothing exceptional about its circumstances?)
- Is this a bad idea? And if so, why?