gpt4 book ai didi

c# - Exception.Data 和异常处理问题

转载 作者:行者123 更新时间:2023-12-02 19:43:02 25 4
gpt4 key购买 nike

我有几个关于异常的问题。

1) 当你击中捕捉 block 时,吞咽到底意味着什么?我认为它总是被重新抛出或现有的异常被传递到下一个 catch block 。

2) 如果将 Exception.Data 值添加到异常中,我注意到我必须再次抛出;稍后在另一个 catch block 中进一步获取该数据。为什么?

最佳答案

吞掉异常意味着捕获它并且不对其做任何有用的事情。您可能会看到的一个常见现象是:

try
{
DoSomeOperationThatMightThrow();
}
catch (Exception ex) // don't do this!
{
// exception swallowed
}

您通常根本不想捕获基本异常,最好捕获并处理特定的异常类型,理想情况下,您应该只捕获可以在您所在的代码级别执行有用操作的异常类型这在复杂的应用程序中可能很棘手,因为您可能在代码的不同级别处理不同的错误。最高级别的代码可能只捕获严重/致命的异常,较低级别的代码可能捕获可以通过某些错误处理逻辑处理的异常。

如果您确实捕获了异常并需要重新抛出它,请执行以下操作:

try
{
DoSomething();
}
catch (SomeException ex)
{
HandleError(...);

// rethrow the exception you caught
throw;

// Or wrap the exception in another type that can be handled higher up.
// Set ex as the InnerException on the new one you're throwing, so it
// can be viewed at a higher level.
//throw new HigherLevelException(ex);

// Don't do this, it will reset the StackTrace on ex,
// which makes it harder to track down the root issue
//throw ex;
}

关于c# - Exception.Data 和异常处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1408955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com