在 Java 中扩展 Throwable
Java 允许您创建一个全新的 Throwable
子类型,例如:
public class FlyingPig extends Throwable { ... }
现在,很少,我可能会做这样的事情:
throw new FlyingPig("Oink!");
当然还有其他地方:
try { ... } catch (FlyingPig porky) { ... }
我的问题是:
- 这是吗?一个坏主意?如果是这样,为什么?
- 如果这是一个坏主意,可以采取什么措施来防止这种子类型化?
- 既然它是无法预防的(据我所知),那么会导致什么灾难?
- 如果这不是一个坏主意,为什么不呢?
- 如何利用
扩展 Throwable
来创造有用的东西?
- 如何利用
建议的场景#1
我真的想要做这样的事情的场景具有以下属性:
- “事件”是最终发生的事情。这是预期。它绝对不是
Error
,并且当它发生时也没有任何Exception
-al。- 因为它是预期的,所以会有一个
catch
在等待它。它不会“滑过”任何东西。它不会“逃避”任何捕获
常规异常
和/或错误
的尝试。
- 因为它是预期的,所以会有一个
- “事件”发生的情况极其罕见。
- 当发生这种情况时,通常会有很深的堆栈跟踪。
所以现在我想说的也许已经很清楚了:FlyingPig
是详尽递归搜索的结果。
要搜索的对象是存在的:只需在搜索空间的大海中找到它即可。搜索过程将是一个漫长的过程,因此相对昂贵的异常处理成本可以忽略不计。事实上,使用布尔 isFound 标志的传统控制流构造替代方案可能更昂贵,因为必须在整个搜索过程中(很可能在递归的每个级别)不断检查它。该检查在 99.99% 的情况下都会失败,但传播终止条件是绝对必要的。在某种程度上,虽然检查有效,但检查效率低下!
当找到所寻找的对象时,只需抛出
-ing一个FlyingPig
,您就不必因为boolean isFound
的管理而使代码变得混乱> 旗帜。在这方面,代码不仅更干净,而且由于这一省略,它可能运行得更快。
总而言之,可以在这两者之间进行选择:
- 传统的控制流方法
- 使用
布尔值isFound
,连续检查 - 99.99% 的情况下,支票是“浪费”,因为它仍然是
假
- 当它最终变为
true
时,您将停止递归,并且必须确保可以正确展开到初始调用。
- 使用
FlyingPig
方法- 不用理会任何
boolean isFound
。 - 如果找到,只需
抛出 new FlyingPig()
;这是预期的,因此会有一个catch
。 - 不管理
boolean
标志,如果需要继续,则不会浪费检查,无需簿记来手动展开递归等。
- 不用理会任何
问题:
- 这种(ab)使用异常的技术有效吗? (有名字吗?)
- 如果有效,应该
FlyingPig extends Throwable
,还是Exception
就可以了? (尽管它的情况没有什么异常?)
Java lets you create an entirely new subtype of Throwable
, e.g:
public class FlyingPig extends Throwable { ... }
Now, very rarely, I may do something like this:
throw new FlyingPig("Oink!");
and of course elsewhere:
try { ... } catch (FlyingPig porky) { ... }
My questions are:
- Is this a bad idea? And if so, why?
- What could've been done to prevent this subtyping if it is a bad idea?
- Since it's not preventable (as far as I know), what catastrophies could result?
- If this isn't such a bad idea, why not?
- How can you make something useful out of the fact that you can
extends Throwable
?
- How can you make something useful out of the fact that you can
Proposed scenario #1
A scenario where I was really tempted to do something like this has the following properties:
- The "event" is something that will happen eventually. It is expected. It most definitely is not an
Error
, and there's nothingException
-al about when it occurs.- Because it is expected, there will be a
catch
waiting for it. It will not "slip" past anything. It will not "escape" from any attempt tocatch
generalException
and/orError
.
- Because it is expected, there will be a
- The "event" happens extremely rarely.
- When it happens, usually there's a deep stack trace.
So perhaps it's clear now what I'm trying to say: FlyingPig
is the result of an exhaustive recursive search.
The object to be searched exists: it's only a matter of finding it in the big sea that is the search space. The search process will be a long one, so the relatively expensive cost of exception handling is negligible. In fact, the traditional control flow construct alternative of using a boolean isFound
flag may be more expensive, because it has to be checked continuously throughout the search process, most likely at every level of the recursion. This check will fail 99.99% of the time, but it's absolutely necessary to propagate the termination condition. In a way, while effective, the check is inefficient!
By simply throw
-ing a FlyingPig
when the sought object is found, you don't have to clutter the code with the management of the boolean isFound
flag. Not only is the code cleaner in that regard, but it may run faster due to this omission.
So to summarize, the choice is between these two:
- Traditional control-flow approach
- Use a
boolean isFound
, checked continuously - 99.99% of the time, the check is a "waste", because it'd still be
false
- When it eventually becomes
true
, you stop recursing and you have to make sure that you can properly unwind to the initial call.
- Use a
FlyingPig
approach- Don't bother with any
boolean isFound
. - If found, just
throw new FlyingPig()
; it's expected, so there will be acatch
for it. - No management of
boolean
flag, no wasted check if you need to keep going, no bookkeeping to manually unwind the recursion, etc.
- Don't bother with any
Questions:
- Is this technique of (ab)using exception valid? (Is there a name for it?)
- If valid, should
FlyingPig extends Throwable
, or isException
just fine? (even though there's nothing exceptional about its circumstances?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想说这是一个非常糟糕的主意。许多代码的实现都是基于这样的假设:如果您捕获了
Error
和Exception
,那么您就捕获了所有可能的异常。大多数教程和教科书都会告诉你同样的事情。通过创建 Throwable 的直接子类,您可能会产生各种维护和互操作性问题。我想不出有什么充分的理由来扩展
Throwable
。改为扩展Exception
或RuntimeException
。编辑 - 回应OP提出的场景#1。
异常是处理“正常”流量控制的一种非常昂贵的方法。在某些情况下,我们谈论的是执行数千条额外指令来创建、抛出和捕获异常。如果您打算忽略公认的智慧并使用异常进行非异常流程控制,请使用
Exception
子类型。试图通过将 is 声明为 Throwable 的子类型来假装某件事是“事件”而不是“异常”,不会取得任何成果。然而,将异常与错误、错误、错误等等混为一谈是错误的。使用
Exception
的子类表示“不是错误、差错、错误或其他任何内容的异常事件”没有什么问题。关键是该事件应该例外;即不寻常,很少发生,...总之,
FlyingPig
可能不是错误,但这没有理由不将其声明为Exception
的子类型代码>.I'd say that it is a really bad idea. A lot of code is implemented on the assumption that if you catch
Error
andException
you have caught all possible exceptions. And most tutorials and textbooks will tell you the same thing. By creating a direct subclass ofThrowable
you are potentially creating all sorts of maintenance and interoperability problems.I can think of no good reason to extend
Throwable
. ExtendException
orRuntimeException
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 ofThrowable
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 ofException
.在我看来,这不是一个好主意:
异常应该不用于流量控制。如果我必须命名这种技术,我会称之为代码味道或反模式。
另请参阅:
某些情况下,您可能希望catch
Throwable
而不仅仅是捕获Exception
但也有Error
,但这种情况很少见,人们通常不会捕获Throwable
。但我未能找到您想要抛出Throwable
子类的情况。而且我还认为,扩展 Throwable 并不会让事情看起来不那么“异常”,反而会让事情看起来更糟——这完全违背了初衷。
所以总而言之,如果你真的想抛出一些东西,那就抛出
Exception
的子类。另请参阅:
In my opinion, it's not a good idea:
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:
There might be situations where you want to catch
Throwable
to not only catchException
but alsoError
but it's rare, people usually don't catchThrowable
. But I fail at finding a situation where you'd like to throw a subclass ofThrowable
.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:
以下是 HotSpot 架构师 John Rose 的博客文章:
http://blogs.oracle.com /jrose/entry/longjumps_considered_inexpense
它是关于“滥用”流量控制的异常。用例略有不同,但是..
简而言之,如果您预先分配/克隆异常以防止创建堆栈跟踪,那么它的效果非常好。
我认为如果对客户“隐藏”这种技术是合理的。
IE,你的 FlyingPig 应该永远无法离开你的库(所有公共方法都应该传递保证不抛出它)。保证这一点的一种方法是使其成为受检查的异常。
我认为扩展 Throwable 的唯一理由是因为您希望允许人们传入具有 catch(Exception e) 子句的回调,并且您希望他们忽略您的结果。我刚好可以买那个...
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...
org.junit.Test
注释包含None
类,它扩展了Throwable
并用作expected
的默认值代码>注释参数。The
org.junit.Test
annotation includes theNone
class which extendsThrowable
and is used as the default value for theexpected
annotation parameter.如果您可以证明 FlyingPig 与 Error 和 Exception 不同的原因是什么,以至于它不适合作为其中任何一个的子类,那么创建它并没有什么根本性的错误。
我能想到的最大问题是在务实的世界中,有时有正当理由要捕获java.lang.Exception。你的新类型的 throwable 将直接飞过 try-catch 块,这些块具有抑制(或记录、包装等)每个可能的非致命问题的合理期望。
另一方面,如果您正在对一个不合理地抑制 java.lang.Exception 的旧系统进行维护,那么您可以绕过它。 (假设真诚地呼吁时间来实际正确修复它被拒绝)。
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).
扩展 Throwable 使其能够抛出(和处理)自定义异常并没有什么问题。但是,您应该记住以下几点:
因此,假设您的代码库中有以下异常类:
和一些方法
现在,您可以有一些调用这些方法的代码,如下所示:
请注意,当我们调用
bar()
时,我们可以捕获Pig
,因为FlyingPig
和Swine
都扩展了Pig
。如果您想要执行相同的操作来处理任一异常,这非常有用。但是,您可以以不同的方式处理它们: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:
So, suppose you have the following exception classes in your code base:
And some methods
Now, you could have some code that calls these methods like this:
Note that when we call
bar()
, we can just catchPig
, since bothFlyingPig
andSwine
extendPig
. This is useful if you want to do the same thing to handle either exception. You could, however, handle them differently:玩吧!框架使用类似的东西来处理请求。请求处理经过许多层(路由、中间件、控制器、模板渲染),在最后一层渲染的 HTML 为 包裹在一个 throwable 中并抛出,最顶层捕获、解开并发送到客户。因此,涉及的许多层中的方法都不需要显式返回响应对象,也不需要将响应对象作为参数传递以进行传播和修改。
我对细节有点粗略。你可以看一下Play的代码!框架的细节。
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.