Extending Throwable in Java

前端 未结 7 1368
长发绾君心
长发绾君心 2020-12-16 10:47

Java lets you create an entirely new subtype of Throwable, e.g:

public class FlyingPig extends Throwable { ... }

Now, very

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 11:17

    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.

提交回复
热议问题