CSharp · Console
using System;
public class Program
{
public static void Main()
{
ExceptionTesting et = new ExceptionTesting();
Console.WriteLine("Bad exception handling example, throws 'ex' rather than just throwing. In this case we lose some of the stack trace");
try
{
et.CatchExceptionThenThrowEx();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.WriteLine("Note how in the above stacktrace, it looks like the exception originated from CatchExceptionThenThrowEx, where it actually originated several function calls deeper.");
Console.WriteLine("\n\n");
Console.WriteLine("Good exception handling example, throws when an exception occurs. In this case we keep the entirety of the stack trace");
try
{
et.CatchExceptionThenThrow();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.WriteLine("Note how in the above stacktrace, we can see that the exception actually originaed in FinishTHings.");
}
}
public class ExceptionTesting
{
public void CatchExceptionThenThrow()
{
try
{
StartThings();
}
catch (Exception)
{
throw;
}
}
public void CatchExceptionThenThrowEx()
{
try
{
StartThings();
}
catch (Exception ex)
{
throw ex;
}
}
private void StartThings()
{
this.ProcessingThings();
}
private void ProcessingThings()
{
this.FinishThings();
}
private void FinishThings()
{
throw new Exception("Throw that exception");
}
}