相关疑难解决方法(0)

"throw"和"throw ex"之间有区别吗?

有些帖子询问这两者之间的区别是什么.
(为什么我还要提这个...)

但我的问题是不同的,我称之为"抛出前"在另一个错误的神像处理方法.

public class Program {
    public static void Main(string[] args) {
        try {
            // something
        } catch (Exception ex) {
            HandleException(ex);
        }
    }

    private static void HandleException(Exception ex) {
        if (ex is ThreadAbortException) {
            // ignore then,
            return;
        }
        if (ex is ArgumentOutOfRangeException) { 
            // Log then,
            throw ex;
        }
        if (ex is InvalidOperationException) {
            // Show message then,
            throw ex;
        }
        // and so on.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果try & catch用于Main,那么我会throw; …

.net c# exception-handling exception

414
推荐指数
8
解决办法
18万
查看次数

如何重新抛出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万
查看次数

捕获/抛出堆栈跟踪丢失错误的行号

我已经尝试了一些关于如何在抛出异常时在堆栈跟踪中保留正确行号的建议。最常见的就是接住然后扔掉,但这不起作用。以下是我尝试过的一些:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
private void test()
{
    try
    {
        int a = 1;
        int b = 0;
        int x = 0;
        x = a / b;
    }
    catch 
    {
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

还有 catch 块的一些变化。

catch (Exception)
{
    throw;
}

catch (Exception e)
{
   throw;
}

catch (Exception e)
{
    throw e;
}
Run Code Online (Sandbox Code Playgroud)

所有这些都在抛出行和消息框行上报告错误 - 永远不会在除以 0 的行上报告错误。如果我在 test() 函数内部中断,它确实会显示正确的行 #,但在抛出后不会显示错误。唯一有效的方法是在 test() 函数中不要有任何 try/catch。但当然我希望能够捕获错误并重新抛出它们并保持堆栈跟踪正确。那么这是如何做到的呢? …

c# try-catch

6
推荐指数
2
解决办法
907
查看次数

标签 统计

c# ×3

.net ×2

exception ×2

exception-handling ×1

try-catch ×1