捕获异常并在 C# 中重新抛出 - 它可以保持其类型吗?

Catching an Exception and rethrowing in C# - can it keep its type?

我们有一段业务关键的遗留代码,方法比较多,代码比较乱。没有测试框架,而且它是如此重要,我们的调试能力是有限的。日志消息没有用 - "object not set to an instance of an object"... 在调用其他方法的 500 行代码中的某处。这是因为方法体很大 try/catch 并捕获了特定的异常。

我想建议我们通过更好的错误记录来解决这个问题,但我想尽量减少我对方法的影响。我需要它照常进行,因为它对业务至关重要。因此,人们不敢触摸它,所以我需要在提出这个想法之前检查我的理解。正如我所说,我不能在不编写测试工具的情况下自己进行更改和测试。由于消防,我没有时间去做,这是周五的最后一件事。

我认为这样做的一个好方法是在方法主体中插入较小的 try/catch 块以捕获所有异常,记录一些有用的信息,然后重新抛出到下面的特定捕获处理程序。

public int SomeFunc()
{
    try
    {
        // many lines of code

        // I want to wrap this call that gives us problems
        try
        {
            BrittleFunc(arg1, arg2, ..., arg15);
        }
        catch (Exception e)
        {
            // Log the params for repro in unit test and then rethrow
            Log(args);
            throw;
        }

        // many more lines of code

    }
    catch(CustomException1 e)
    {
        // Do something
    }
    // more...
    catch(CustomException9 e)
    {
        // Do something
    }
    return someInt;
}

在我内心 try/catch 我可以编写与底部匹配的特定捕获处理程序,但这看起来会很乱。

如果我在 catch(Exception e) 中捕获 CustomException2 并重新抛出,它会在 catch(CustomException2 e) 中结束吗?

是的,你可以做到。在你的第一个 catch 中,异常被简单地视为基础 Exception 但是当你重新抛出它时,下一个 catch 将捕获它,因为它是真实类型。

重新抛出异常时请使用throw;而不是thrown ex;see here why