在 Java 中扩展 Throwable

发布于 2024-08-31 05:50:47 字数 2020 浏览 3 评论 0原文

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?

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 nothing Exception-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 to catch general Exception and/or Error.
  • 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.
  • FlyingPig approach
    • Don't bother with any boolean isFound.
    • If found, just throw new FlyingPig(); it's expected, so there will be a catch for it.
    • No management of boolean flag, no wasted check if you need to keep going, no bookkeeping to manually unwind the recursion, etc.

Questions:

  • Is this technique of (ab)using exception valid? (Is there a name for it?)
  • If valid, should FlyingPig extends Throwable, or is Exception just fine? (even though there's nothing exceptional about its circumstances?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

轮廓§ 2024-09-07 05:50:47

我想说这是一个非常糟糕的主意。许多代码的实现都是基于这样的假设:如果您捕获了 ErrorException,那么您就捕获了所有可能的异常。大多数教程和教科书都会告诉你同样的事情。通过创建 Throwable 的直接子类,您可能会产生各种维护和互操作性问题。

我想不出有什么充分的理由来扩展 Throwable。改为扩展 ExceptionRuntimeException

编辑 - 回应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 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.

挖鼻大婶 2024-09-07 05:50:47

这种(ab)使用异常的技术有效吗? (有名字吗?)

在我看来,这不是一个好主意:

异常应该不用于流量控制。如果我必须命名这种技术,我会称之为代码味道或反模式。

另请参阅:

如果有效,FlyingPig 应该扩展 Throwable,还是 Exception 就可以了? (即使它的情况没有什么异常?)

某些情况下,您可能希望catch Throwable 而不仅仅是捕获Exception 但也有 Error,但这种情况很少见,人们通常不会捕获Throwable。但我未能找到您想要抛出 Throwable 子类的情况。

而且我还认为,扩展 Throwable 并不会让事情看起来不那么“异常”,反而会让事情看起来更糟——这完全违背了初衷。

所以总而言之,如果你真的想抛出一些东西,那就抛出Exception的子类。

另请参阅:

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:

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:

神经大条 2024-09-07 05:50:47

以下是 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...

仅冇旳回忆 2024-09-07 05:50:47

org.junit.Test 注释包含 None 类,它扩展了 Throwable 并用作 expected 的默认值代码>注释参数。

The org.junit.Test annotation includes the None class which extends Throwable and is used as the default value for the expected annotation parameter.

自由如风 2024-09-07 05:50:47

如果您可以证明 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).

悲念泪 2024-09-07 05:50:47

随着这个问题的发展,我明白了
我误解了要点
原来的问题,所以一些
其他答案可能更多
相关的。我会保留这个答案
在这里,因为它可能仍然有帮助
其他有类似问题的人,
并在搜索时找到此页面
他们的问题的答案。

扩展 Throwable 使其能够抛出(和处理)自定义异常并没有什么问题。但是,您应该记住以下几点:

  • 使用尽可能最具体的异常是一个好主意。它将允许调用者以不同的方式处理不同类型的异常。记住异常的类层次结构很重要,因此您的自定义异常应该扩展另一种尽可能接近您的异常的 Throwable 类型。
  • 扩展 Throwable 可能级别太高。尝试扩展 Exception 或 RuntimeException (或者更接近引发异常的原因的较低级别异常)。请记住 RuntimeException 和 Exception 之间的区别。
  • 对引发异常(或异常的子类)的方法的调用需要包装在能够处理异常的 try/catch 块中。当您预计由于情况可能超出您的控制(例如,网络出现故障)而出现问题时,这非常有用。
  • 对抛出 RuntimeException(或其子类)的方法的调用不需要包装在可以处理异常的 try/catch 块中。 (当然可以,但不需要。)这更多的是针对确实不应该预期的异常。

因此,假设您的代码库中有以下异常类:

public class Pig extends Throwable { ... }
public class FlyingPig extends Pig { ... }
public class Swine extends Pig { ... }
public class CustomRuntimeException extends RuntimeException { ... }

和一些方法

public void foo() throws Pig { ... }
public void bar() throws FlyingPig, Swine { ... }
// suppose this next method could throw a CustomRuntimeException, but it
// doesn't need to be declared, since CustomRuntimeException is a subclass
// of RuntimeException
public void baz() { ... } 

现在,您可以有一些调用这些方法的代码,如下所示:

try {
    foo();
} catch (Pig e) {
    ...
}

try {
    bar();
} catch (Pig e) {
    ...
}

baz();

请注意,当我们调用 bar() 时,我们可以捕获 Pig,因为 FlyingPigSwine 都扩展了 Pig。如果您想要执行相同的操作来处理任一异常,这非常有用。但是,您可以以不同的方式处理它们:

try {
    bar();
} catch (FlyingPig e) {
    ...
} catch (Swine e) {
    ...
}

As this question has evolved, I see
that I misunderstood the point of the
original question, so some of the
other answers are probably more
relevant. I will leave this answer up
here, since it may still be helpful to
others who have a similar question,
and find this page while searching for
an answer to their question.

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:

  • Using the most specific exception possible is a great idea. It will allow the caller to handle different types of exceptions differently. The class hierarchy of the exception is important to keep in mind, so your custom exception should extend another type of Throwable that is as close to your exception as possible.
  • Extending Throwable might be too high-level. Try extending Exception or RuntimeException instead (or a lower-level exception that is closer to the reason you are throwing an exception). Keep in mind the difference between a RuntimeException and an Exception.
  • A call to a method that throws an Exception (or a subclass of Exception) will need to be wrapped in a try/catch block that is capable of dealing with the exception. This is good for cases when you expect things to go wrong, due to circumstances that may be out of your control (eg, the network being down).
  • A call to a method that throws a RuntimeException (or a subclass of it) does not need to be wrapped in a try/catch block that can handle the exception. (It certainly could be, but it doesn't need to be.) THis is more for exceptions that really shouldn't be expected.

So, suppose you have the following exception classes in your code base:

public class Pig extends Throwable { ... }
public class FlyingPig extends Pig { ... }
public class Swine extends Pig { ... }
public class CustomRuntimeException extends RuntimeException { ... }

And some methods

public void foo() throws Pig { ... }
public void bar() throws FlyingPig, Swine { ... }
// suppose this next method could throw a CustomRuntimeException, but it
// doesn't need to be declared, since CustomRuntimeException is a subclass
// of RuntimeException
public void baz() { ... } 

Now, you could have some code that calls these methods like this:

try {
    foo();
} catch (Pig e) {
    ...
}

try {
    bar();
} catch (Pig e) {
    ...
}

baz();

Note that when we call bar(), we can just catch Pig, since both FlyingPig and Swine extend Pig. This is useful if you want to do the same thing to handle either exception. You could, however, handle them differently:

try {
    bar();
} catch (FlyingPig e) {
    ...
} catch (Swine e) {
    ...
}
像极了他 2024-09-07 05:50:47

玩吧!框架使用类似的东西来处理请求。请求处理经过许多层(路由、中间件、控制器、模板渲染),在最后一层渲染的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文