1

it is allowed to use custom exception, where the exception can be thrown like below.

  try
{
    int foo = int.Parse(token);
}
catch (FormatException ex)
{
    //Assuming you added this constructor
    throw new ParserException(
      $"Failed to read {token} as number.", 
      FileName, 
      LineNumber, 
      ex);
}

But in a normal try catch block, it says , throwing exceptions will clear the stacktrace.

 try
      {
        ForthCall();
      }
      catch (Exception ex)
      {
        throw ex;
      }

So in custom exception,how it managed to use throw exception, without clear the stacktrace?

Graham
  • 7,431
  • 18
  • 59
  • 84
Tom Cruise
  • 1,395
  • 11
  • 30
  • 58
  • 3
    You pass the original exception from try block(FormatException) as inner exception in constructor of ParserException, so you can can get the original stack trace through the InnerException member – Den Aug 29 '16 at 04:45
  • How do you say it as inner exception? – Tom Cruise Aug 29 '16 at 05:20
  • According to your code from the link you mentioned. However this link does't provide complete implementation of contructor you used. Just modify this one ParserException(string msg, Exception inner) : base(msg, inner) { }. so while catching your custom excexption you can get the original stack as YourCustomExceptionObject.InnerException.StackTrace – Den Aug 29 '16 at 05:43
  • just say `throw` not `throw ex` – pm100 Sep 29 '17 at 17:57

2 Answers2

0

There are several ways this can be done.

As mentioned in this link In C#, how can I rethrow InnerException without losing stack trace?, you can use the ExceptionDispatchInfo Class with code similar to

try
{
    task.Wait();
}
catch(AggregateException ex)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}

Another way is to have your handler return a boolean, whether the exception was handled or not, so you can use this in your catch clause:

catch (Exception ex) {
  if (!HandleException(ex)) {
    throw;
  }
}

where HandleException is your custom Exception handler. Gotten from this link: How to throw exception without resetting stack trace?

Community
  • 1
  • 1
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41
0

Whenever you use throw with an exception object, it fills in the stack trace at that point. (Compare to Java, which populates stack traces when an exception is constructed.)

If you use throw without an exception object, which you can only do in a catch clause, the caught exception object is re-throw without alteration.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72