3

I was trying out some code in my catch method, and I wanted to try out the exception that it generates. but in order to reach the catch method, I need to crash my program, so it'll be caught and create an exception.

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?

Steven
  • 1,996
  • 3
  • 22
  • 33

3 Answers3

10
try
{
    throw new Exception();
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Magnus
  • 45,362
  • 8
  • 80
  • 118
6

throw new Exception("Test"); is a reliable way.

You could even include something more useful than "Test".

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

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

Usually this is something that should not be applied, especially if you are programming on PLC level. But in the C# world it is just an easy mosquito sting.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76