异常处理
catch (Exception ex)
{
DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
msg = "Unable to save data";
status = false;
}
如果我遇到错误,这段代码将抛出错误状态。
相反,我应该抛出 New 异常。 这是正确的方法吗? 我怎样才能以更好的方式处理异常。
catch (Exception ex)
{
DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
msg = "Unable to save data";
status = false;
}
This piece of code would throw an status as false, if i encounter an error.
Instead should i thrown New exception.
Is this the right way.
How can i handle exception in a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更喜欢抛出异常而不是返回错误代码/状态。
返回错误代码意味着调用者应该始终记住检查它。抛出异常允许调用代码决定要做什么(通常决策越高,做出的效果就越好)。
Prefer throwing exceptions to returning error codes/status.
Returning an error code means the caller should always remember to check for it. Throwing the exception allows the calling code to make the decision of what to do (an normally the higher up the decision, the better it can be made).
首先,不要捕获
Exception
。捕获特定的子类。其次,是的,底层的 IOException(如下所示)可能应该包装在特定于应用程序的异常中。例如,您可以:
然后您
也可以参见: 抛出
异常
,抛出新的和旧的异常,滚动你自己的。这只是其中的一小部分,还有很多关于异常处理、链接等的精彩 SO Q+A。 维基图书。另请阅读Oded的答案并仔细考虑...您的异常应该封装任何状态(错误代码) 、标志等)是外部代码从该条件中恢复所必需的——或者它应该是一个不可恢复的条件(请参阅
RuntimeException
)。最后,规范的Effective Java参考:第 43 项:抛出适合抽象的异常。
First, don't catch
Exception
. Catch a specific subclass.Second, yes it may be that an underlying
IOException
, which is what this looks like, should be wrapped in an app-specific exception. You could have, for instance:And you could then
See also: Throwing
Exception
, Throwing new and old exceptions, Rolling your own. That's just a few, there are a bunch of great SO Q+A's on exception handling, chaining, etc. Some useful best-practices stuff outlined at WikiBooks.Also read Oded's answer and think it through... your exception should encapsulate whatever status (error codes, flags, etc...) are required for the outer code to recover from the condition -- or it should be an unrecoverable condition (see
RuntimeException
).Finally, the canonical Effective Java reference: Item 43: Throw Exceptions Appropriate to the Abstraction.