3

I want to be able to get access to e.ErrorDetails contents when an exception occurs in a try/catch block, but unfortunately I can't.

How could I do this without parsing the entire exception object?

try
{...}
catch (Exception e)
{Console.WriteLine(e.ErrorDetails);} //compile error!

Thank you

enter image description here

2
  • What type is e? Is it Exception or some derived class?
    – SomeBody
    Dec 16, 2020 at 8:36
  • @SomeBody, yes it is the Exception Object.
    – NoChance
    Dec 16, 2020 at 8:51

1 Answer 1

4

You need to have an expression of type IScriptEngineException. The simplest approach to that is probably to catch that specific exception. You can't use the interface for that directly, but you can use an exception filter to have the same effect as if you wrote catch (IScriptEngineException ex):

try
{
    // ...
}
catch (Exception e) when (e is IScriptEngineException ex)
{
    Console.WriteLine(ex.ErrorDetails);
}
// Potentially a more general catch block here

You should consider carefully whether you want to have a more general catch block (catching all exceptions) - without more context, we can't give much advice for that. "Catch all" blocks are generally appropriate only at the top level of a program - e.g. to avoid taking a server down when a single request fails, or to give diagnostic information in a console app before exiting.

3
  • Thank you for taking the time to answer my question. When I do this, I get the compilation error message: The type caught or thrown must be derived from System.Exception ClearScript-0
    – NoChance
    Dec 16, 2020 at 8:49
  • 1
    @NoChance: Try now - not that this requires C# 7 due to pattern matching. If you need a solution for older versions, you can use as within the catch block instead.
    – Jon Skeet
    Dec 16, 2020 at 8:54
  • 1
    Mr. Skeet you are super! Thank you not only for the help but also for your willing to respond so quickly to a stranger 1000 miles away. I admire your contribution to help strangers with passion. Best wishes and please stay safe.
    – NoChance
    Dec 16, 2020 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.