为什么重新抛出异常? [英] Why Re-throw Exceptions?

查看:255
本文介绍了为什么重新抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到以下代码了很多次:

I've seen the following code many times:

try
{
    ... // some code
}
catch (Exception ex)
{
    ... // Do something
    throw new CustomException(ex);

    // or
    // throw;

    // or
    // throw ex;
}

您能否解释重新抛出异常的目的?是否遵循异常处理中的模式/最佳做法? (我已经在某个地方看到它被称为Caller Inform模式?)

Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)

推荐答案

如果您需要,重新查找相同的异常很有用例如,记录异常,但不能处理它。

Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it.

抛出一个新的异常,包装捕获的异常对抽象是有好处的。例如,您的图书馆使用第三方库,它会抛出您的库的客户端不了解的异常。在这种情况下,您将它包装成一个更常见的异常类型,并将其替换为。

Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead.

这篇关于为什么重新抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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