通常我将所有Main方法代码放在try/catch块中,如下所示:
public static void Main(string[] args)
{
try
{
// code
}
catch (Exception e)
{
// code
}
}
Run Code Online (Sandbox Code Playgroud)
我这样做是为了防止任何异常设法从程序逻辑的其余部分中滑出,从而允许我对它做一些事情,例如将其显示到控制台,将其记录到文件等等.但是,我被告知这是不好的做法.
你认为这是不好的做法吗?
我一直认为"throw"和"throw ex"之间的区别在于单独抛出并没有重置异常的堆栈跟踪.
不幸的是,这不是我正在经历的行为; 这是一个复制我的问题的简单示例:
using System;
using System.Text;
namespace testthrow2
{
class Program
{
static void Main(string[] args)
{
try
{
try
{
throw new Exception("line 14");
}
catch (Exception)
{
throw; // line 18
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这段代码能够从第14行开始打印一个callstack; 然而,callstack从第18行开始.当然,它在样本中没什么大不了的,但在我的实际应用中,丢失初始错误信息是非常痛苦的.
我错过了一些明显的东西吗 有没有其他方法来实现我想要的(即重新抛出异常而不丢失堆栈信息?)
我正在使用.net 3.5
在网上引用了很多文档,尤其是关于SO的文档,例如:在C#中重新抛出异常的正确方法是什么? "扔e"之间应该有区别 和"扔".
但是,来自:http://bartdesmet.net/blogs/bart/archive/2006/03/12/3815.aspx,
这段代码:
using System;
class Ex
{
public static void Main()
{
//
// First test rethrowing the caught exception variable.
//
Console.WriteLine("First test");
try
{
ThrowWithVariable();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
//
// Second test performing a blind rethrow.
//
Console.WriteLine("Second test");
try
{
ThrowWithoutVariable();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
private static void BadGuy()
{
//
// Some nasty behavior.
//
throw new Exception();
}
private …Run Code Online (Sandbox Code Playgroud)