简体   繁体   English

我如何测试try-catch?

[英]How do I test a try-catch?

I was trying out some code in my catch method, and I wanted to try out the exception that it generates. 我在我的catch方法中尝试了一些代码,我想尝试它生成的异常。 but in order to reach the catch method, I need to crash my program, so it'll be caught and create an exception. 但是为了达到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());
    }
}

Now I wonder, what's an easy, and simple to memorise, line of code that surely makes your program reach that catch method and generate an exception? 现在我想知道,什么是一个简单易记的代码行,肯定会让你的程序达到catch方法并产生异常?

try
{
    throw new Exception();
}

throw new Exception("Test"); is a reliable way. 是一种可靠的方式。

You could even include something more useful than "Test" . 你甚至可以包含比"Test"更有用的东西。

one of the things I like to use in such cases is this: 我喜欢在这种情况下使用的一件事是这样的:

int div = 0;

int res = 3/div;

this will throw a DivideByZeroException 这将抛出DivideByZeroException

Usually this is something that should not be applied, especially if you are programming on PLC level. 通常这是不应用的,特别是如果您在PLC级别编程。 But in the C# world it is just an easy mosquito sting. 但在C#世界中它只是一个容易蚊子刺痛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM