2016-09-29 66 views
0

我已经尝试了几个关于如何在抛出异常时在堆栈跟踪中保留正确行号的建议。最常见的只是抓住并抛出,但这不起作用。这里有一些我已经尝试过:catch/throw堆栈跟踪丢失错误的行号

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; 
    } 
} 

和catch块的几个变化。

catch (Exception) 
{ 
    throw; 
} 

catch (Exception e) 
{ 
    throw; 
} 

catch (Exception e) 
{ 
    throw e; 
} 

所有在罚球线和消息框行这些报告错误的 - 永远不要对由0.1分。如果我的测试()函数内断行,但它显示正确的行号,但被抛出后不会。有效的唯一方法是在test()函数中没有任何try/catch。但我当然希望能够捕捉错误并重新抛出错误,并保持堆栈跟踪正确。那么这是如何完成的?

谢谢。

+0

'throw new Exception(“See InnerException”,ex);'catcher可以查看被捕获的异常的InnerException属性以查看原始堆栈跟踪等 –

+0

http://stackoverflow.com/questions/22623/best-实践捕捉和重新抛出净例外 – hatchet

+0

实际上更接近http://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack - 跟踪......但是很惊讶'ExceptionDispatchInfo'只在这个@hatchet中被评论。 – TylerY86

回答

0

在发布时间,您将不会有行号,因为从*.pdb文件中检索到的行数包含所有编译符号。
因此,如果您计划在发布/生产中获得确切的生产线号,您必须复制pdb文件

0

最简单的方法是简单地删除测试中的try catch。如果这不是一个选项,如上面的注释中提到的那样,您可以抛出一个新的异常,传入旧的异常并查找实际堆栈跟踪信息的内部异常。

private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     test(); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.InnerException.ToString()); 
    } 
} 

public void test() 
{ 
    try 
    { 
     int a = 1; 
     int b = 0; 
     int x = 0; 
     x = a/b; 
    } 
    catch (Exception e) 
    { 
     throw new Exception("inner exception", e); 
    } 
} 
0

TylerY86的回答为我工作。当错误冒起来时,它会给出很多额外的东西,但它确实给出了适当的行#。

谢谢!