相关疑难解决方法(0)

如何重新抛出InnerException而不会丢失C#中的堆栈跟踪?

我通过反射调用一种可能导致异常的方法.如何在没有包装器反射的情况下将异常传递给调用者?
我正在重新抛出InnerException,但这会破坏堆栈跟踪.
示例代码:

public void test1()
{
    // Throw an exception for testing purposes
    throw new ArgumentException("test1");
}

void test2()
{
    try
    {
        MethodInfo mi = typeof(Program).GetMethod("test1");
        mi.Invoke(this, null);
    }
    catch (TargetInvocationException tiex)
    {
        // Throw the new exception
        throw tiex.InnerException;
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# exception

290
推荐指数
9
解决办法
7万
查看次数

在.NET异常中保留原始StackTrace/LineNumbers

理解throw exthrow之间的区别,为什么在这个例子中保留了原始的StackTrace:

    static void Main(string[] args)
    {
        try
        {
            LongFaultyMethod();
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
    }

    static void LongFaultyMethod()
    {
        try
        {
            int x = 20;
            SomethingThatThrowsException(x);
        }
        catch (Exception)
        {
            throw;
        }
    }

    static void SomethingThatThrowsException(int x)
    {
        int y = x / (x - x);
    }
Run Code Online (Sandbox Code Playgroud)

但不是在这一个:

    static void Main(string[] args)
    {
        try
        {
            LongFaultyMethod();
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
    }

    static void LongFaultyMethod()
    {
        try
        {
            int x = …
Run Code Online (Sandbox Code Playgroud)

.net exception line-numbers

15
推荐指数
1
解决办法
2198
查看次数

标签 统计

.net ×2

exception ×2

c# ×1

line-numbers ×1