为什么我不应该在“try"-“catch"中包装每个块? [英] Why should I not wrap every block in "try"-"catch"?

查看:36
本文介绍了为什么我不应该在“try"-“catch"中包装每个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为,如果一个方法可以抛出异常,那么不使用有意义的 try 块来保护这个调用是鲁莽的.

I have always been of the belief that if a method can throw an exception then it is reckless not to protect this call with a meaningful try block.

我刚刚发布了你应该总是包装可以抛出 try、catch 块的调用."到 这个问题 并被告知这是非常糟糕的建议" - 我想了解原因.

I just posted 'You should ALWAYS wrap calls that can throw in try, catch blocks.' to this question and was told that it was 'remarkably bad advice' - I'd like to understand why.

推荐答案

一个方法应该只在它可以以某种合理的方式处理异常时捕获异常.

A method should only catch an exception when it can handle it in some sensible way.

否则,向上传递,希望调用堆栈更高的方法可以理解它.

Otherwise, pass it on up, in the hope that a method higher up the call stack can make sense of it.

正如其他人所指出的,在调用堆栈的最高级别设置一个未处理的异常处理程序(带日志记录)是一种很好的做法,以确保记录任何致命错误.

As others have noted, it is good practice to have an unhandled exception handler (with logging) at the highest level of the call stack to ensure that any fatal errors are logged.

这篇关于为什么我不应该在“try"-“catch"中包装每个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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