Extending Throwable in Java

跟風遠走 提交于 2019-11-29 05:26:54

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.

Pascal Thivent

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:

rjw

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

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

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

pkaeding

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

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.

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