Extending Throwable in Java

两盒软妹~` 提交于 2019-11-27 22:58:49

问题


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?)

回答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.




回答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:

  • Throwing exceptions to control flow - code smell?

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:

  • When should Throwable be used instead of new Exception?



回答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...




回答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.




回答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).




回答6:


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) {
    ...
}



回答7:


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.



来源:https://stackoverflow.com/questions/2755972/extending-throwable-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!