Extending Throwable in Java

前端 未结 7 1361
长发绾君心
长发绾君心 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:01

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

提交回复
热议问题