我如何测试try-catch?

Ste*_*ven 3 c# try-catch

我在我的catch方法中尝试了一些代码,我想尝试它生成的异常.但是为了达到catch方法,我需要崩溃我的程序,所以它会被捕获并创建一个异常.

try
{
    //do something
}
catch (Exception ex)
{
    MessageBox.Show("There was an error, please contact the staff");
    using (StreamWriter writer = new StreamWriter(Application.StartupPath + "\\Crashlog\\Crashfile.txt"))
    {
        writer.WriteLine(ex.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想知道,什么是一个简单易记的代码行,肯定会让你的程序达到catch方法并产生异常?

Mag*_*nus 9

try
{
    throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)


Bat*_*eba 5

throw new Exception("Test"); 是一种可靠的方式.

你甚至可以包含一些更有用的东西"Test".