Extending Throwable in Java

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

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

提交回复
热议问题