是“抛出可投掷的”良好的做法 [英] Is "throws Throwable" good practice

查看:65
本文介绍了是“抛出可投掷的”良好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去我会用以下方法读取大量代码:

In the past I'd read tons of code with methods like:

public Object doSomething() throws Throwable {
    ...
}

通常这样做吗?

什么是专业&缺点?

What are pros & cons?

抛出Trowable 在我看来像是代理橙的方式来完成异常事项

throws Trowable seemed to me like the "Agent Orange" way of getting the Exception- matter done

编辑


  1. 处理方法中的预期异常

  1. Handle expected Exceptions in the Method

抛出意外异常(逐个)

不关心错误

这是要走的路吗?

推荐答案

你不应该抛出 Throwable 。这就是原因。

You should not throw Throwable. Here's why.

Throwable是可以抛出的事物层次结构的顶层,由例外组成和错误。由于错误根据定义来自不可挽回的条件,因此将它们包含在方法声明中是没有意义的。这只留下异常

Throwable is the top of the hierarchy of things that can be thrown and is made up of Exceptions and Errors. Since Errors by definition arise from unsalvagable conditions, it is pointless to include them in your method declaration. That leaves just Exception.

你应该用声明你的方法抛出异常代替。



请注意,的范围越窄更好。

如果您的方法没有生成异常,则声明您的方法为 throws Exception 即可但是调用其他声明为的代码会抛出异常,并且您希望例外来渗透调用堆栈。

Declaring your method to be throws Exception is ok if your method doesn't generate the exceptions, but instead calls other code that is declared as throws Exception and you want exceptions to percolate up the call stack.

如果你的方法是生成异常,那么声明一个更窄的范围,例如抛出IOException,MyProcessingException 等等

If your method is the generating the exception, then declare a narrower range, eg throws IOException, MyProcessingException, etc

这篇关于是“抛出可投掷的”良好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆