views:

342

answers:

7

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?

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 nothing Exception-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 to catch general Exception and/or Error.
  • 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 a FlyingPig when the sought object is found, you don't have to clutter the code with the management of the boolean 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.
  • FlyingPig approach
    • Don't bother with any boolean isFound.
    • If found, just throw new FlyingPig(); it's expected, so there will be a catch for it.
    • No management of boolean flag, no wasted check if you need to keep going, no bookkeeping to manually unwind the recursion, etc.

Questions:

  • Is this technique of (ab)using exception valid? (Is there a name for it?)
  • If valid, should FlyingPig extends Throwable, or is Exception just fine? (even though there's nothing exceptional about its circumstances?)
+2  A: 

As this question has evolved, I see that I misunderstood the point of the original question, so some of the other answers are probably more relevant. I will leave this answer up here, since it may still be helpful to others who have a similar question, and find this page while searching for an answer to their question.

There is nothing wrong with extending Throwable to be able to throw (and handle) custom exceptions. However, you should keep the following points in mind:

  • Using the most specific exception possible is a great idea. It will allow the caller to handle different types of exceptions differently. The class hierarchy of the exception is important to keep in mind, so your custom exception should extend another type of Throwable that is as close to your exception as possible.
  • Extending Throwable might be too high-level. Try extending Exception or RuntimeException instead (or a lower-level exception that is closer to the reason you are throwing an exception). Keep in mind the difference between a RuntimeException and an Exception.
  • A call to a method that throws an Exception (or a subclass of Exception) will need to be wrapped in a try/catch block that is capable of dealing with the exception. This is good for cases when you expect things to go wrong, due to circumstances that may be out of your control (eg, the network being down).
  • A call to a method that throws a RuntimeException (or a subclass of it) does not need to be wrapped in a try/catch block that can handle the exception. (It certainly could be, but it doesn't need to be.) THis is more for exceptions that really shouldn't be expected.

So, suppose you have the following exception classes in your code base:

public class Pig extends Throwable { ... }
public class FlyingPig extends Pig { ... }
public class Swine extends Pig { ... }
public class CustomRuntimeException extends RuntimeException { ... }

And some methods

public void foo() throws Pig { ... }
public void bar() throws FlyingPig, Swine { ... }
// suppose this next method could throw a CustomRuntimeException, but it
// doesn't need to be declared, since CustomRuntimeException is a subclass
// of RuntimeException
public void baz() { ... } 

Now, you could have some code that calls these methods like this:

try {
    foo();
} catch (Pig e) {
    ...
}

try {
    bar();
} catch (Pig e) {
    ...
}

baz();

Note that when we call bar(), we can just catch Pig, since both FlyingPig and Swine extend Pig. This is useful if you want to do the same thing to handle either exception. You could, however, handle them differently:

try {
    bar();
} catch (FlyingPig e) {
    ...
} catch (Swine e) {
    ...
}
pkaeding
This does not address the question, which is whether directly inheriting the rarely-catched Throwable class is safe.
Oak
+4  A: 

The org.junit.Test annotation includes the None class which extends Throwable and is used as the default value for the expected annotation parameter.

Stephen Denne
+1: A throwable thing that's never thrown. Clever.
Donal Fellows
Too clever by half, IMO. `None` could equally have been declared as a regular subclass of `Exception`. And certainly, this is not an example to follow in other situations.
Stephen C
+14  A: 

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.

Stephen C
+1, but I'd say it's almost always a bad idea, unless you know that it's exactly what you want to do.
Stephen Denne
@Stephen Denne - in 10+ years of Java coding, I've yet to come across a situation where extending Throwable would have been a good idea. Granted, it is not impossible that such a situation might exist ...
Stephen C
@Stephen: Regarding cost: I probably should just benchmark this, but I think tens of millions of `boolean` test may be more expensive in the long run than one exception handling. Like I've emphasized, the search is a lengthy one: it may take minutes, even hours. See also my comment on Pascal's answer.
polygenelubricants
@polygenelubricants - the use-case sounds reasonable for exceptions, especially if it *also* significantly simplifies the code.
Stephen C
+3  A: 

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 *un*justifiably suppressing java.lang.Exception, you could cheat around it. (Assuming the sincere appeal for time to actually fix it properly is denied).

Affe
+5  A: 

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 extends Throwable, or is Exception 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:

Pascal Thivent
+1, but you didn't address the fact that handling an exception that happens very rarely may be cheaper than wasting time on traditional control flow that is ineffective 99.99% of the time. Also, when you `throw` a `FlyingPig`, you `catch` a `FlyingPig`. I never proposed that one should `catch (Throwable t)` (which I agree is a bad idea).
polygenelubricants
@polygenelubricants To clarify, I agree with your first remark, the performance cost is not a good argument here. But still, throwing an exception (with a little e) for something that is not exception-al is astonishing. That's not what most readers of the code would expect in my opinion. Regarding the second point, my intention was not to say that you proposed to `catch (Throwable t)` - you didn't - but that this seems to be the only reasonable use of `Throwable` for me (catching it, not throwing it). I've updated my answer, hope things are clearer.
Pascal Thivent
Could you explain this - "Throwing exception is a very expensive operation in Java."? Or at least provide references. As far as I know, filling in the stack trace is expensive, but every other part of exception processing isn't that bad.
Jack Leow
Pascal Thivent
+4  A: 

Here is a blog post from John Rose, a HotSpot architect:

http://blogs.sun.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...

rjw
+1  A: 

The Play! framework uses something like this for request handling. The request processing goes through many layers (routing, middleware, controllers, template rendering) and at the final layer the rendered HTML is wrapped in a throwable and thrown, which the top most layer catches, unwraps and sends to the client. So none of the methods in the many layers involved need to explicitly return a response object, nor do they need to have a response object passed as argument to be propagated and modified.

I am bit sketchy on details. You can look through the code of Play! framework for details.

abhin4v
Is there a name for this idiom that you know of?
polygenelubricants
I don't know the name of this idiom. I just came across it while reading the source of the framework.
abhin4v
It feels like a wormhole - disappear at one point of stack and appear at a different point, without going through the part in between. Not sure if that is a good thing.
abhin4v