Extending Throwable in Java

前端 未结 7 1356
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    2020-12-16 11:05

    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?

提交回复
热议问题