在什么级别和如何适当捕捉异常 [英] At what level and how is appropriate to catch exceptions

查看:126
本文介绍了在什么级别和如何适当捕捉异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是主观的,但应该将异常情况置于最低级别或更高级别。
我要问,因为我通常做

  try 
{
// ..
}
catch
{
// LOG
}

所以当我实现一些低级功能,如

  std :: string read_from_file(const std :: string& file_name); 

我不知道该怎么办:

1)让调用者处理异常

2)catch(log?)并重新抛出

3)catch和change函数,以便bool是返回类型(try中的最后一行返回true; catch中的最后一行是返回false;)。我不喜欢这个,但我看到它完成了很多次。

4)???

解决方案

在可以真正处理的地方,或者没有其他地方可以扔它的水平。



捕捉和重新投递不会处理任何东西,除非你的目的是包装例外的东西更具说明性(例如,Spring持久性将SQLException转换为通过查看SQL错误代码更有意义的东西)。



有时候没有其他地方可以去。没有用户应该看到堆栈跟踪,所以控制器应该捕获所有内容并重定向到友好的错误页面。



您可以捕获并更改返回类型,但用户正在丢失信息。 true / false不会告诉他们与堆栈跟踪相同的信息。发送一个被捕获的例外的成功对我来说并不适合。



如果你不能处理一个异常,那么将它鼓起来就可以了。如果可以处理,请执行此操作。


I know this is subjective, but should exceptions be caught in the lowest level or higher. I ask because I usually do

try 
{
 //..
}
catch
{
 //LOG
}

So when I implement some "low level" function, like

std::string read_from_file(const std::string& file_name);

Im not sure what should I do:
1) let caller handle exception.
2) catch (log?) and rethrow
3) catch and change function so that bool is return type(last line in try is return true; last line in catch is return false;). I dont like this but Ive seen it done many times.
4) ???

解决方案

Catch at the level that can truly handle it or when there is no other place to throw it.

Catching and rethrowing doesn't handle anything, unless your purpose is to wrap an exception in something more illustrative (e.g. Spring persistence wraps SQLException into something more meaningful by looking at SQL error codes).

Sometimes there's no place else to go. No user should ever see a stack trace, so controllers should catch everything and redirect to a friendly error page.

You can catch and change return type, but users are losing information. "true/false" won't tell them the same info as a stack trace. Sending back "success" for a caught exception doesn't feel right to me.

If you can't handle an exception, bubble it up to a layer that can. If you can handle it, do so.

这篇关于在什么级别和如何适当捕捉异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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