异常处理的做法顶级水平与各功能 [英] Exception handling practices top level vs every function

查看:117
本文介绍了异常处理的做法顶级水平与各功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过几种异常处理的方法。我看到的两个最常见的模式是:

I've seen several approaches of exception handling. Two most common patterns I've seen are:


  • 尝试捕获每个函数,记录异常并重新抛出

  • 尝试捕获最上层(像main函数一样),记录异常并重新抛出

如果有一个?

推荐答案

这取决于你的应用程序,是一个设计选择, 1很凌乱。你应该只捕捉准备在某些时候处理的异常,而不是任意捕捉每一个。在大多数语言中,异常会有一个堆栈跟踪,供您查看,因此在每个级别的日志记录是不必要的。当我说处理以某种方式可能是日志和重新抛出,或者它可能是日志,通知用户一些错误,并继续运行

This depends on your application and is a design choice, though option 1 is very messy. You should only catch exceptions you are prepared to handle in someway, not arbitrarily catching every one. In most languages the exception will have a stack trace for you to look at so logging at every level is unnecessary. When I say handle in some way that may be to log and rethrow, or it may be to log, notify the user of some error, and continue to run

作为一个旁注,你不应该在你的代码中使用异常作为逻辑。如果你发现自己使用try catch块作为流控制,那么你应该想到重新设计。例外只是,例外。

As a side note, you should not be using exceptions as logic in your code. If you find yourself using try catch blocks as flow control then you should think of a redesign. Exceptions are just that, exceptional.

这篇关于异常处理的做法顶级水平与各功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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