Home > OS >  Can I rethrow an existing exception in an expression switch case?
Can I rethrow an existing exception in an expression switch case?

Time:01-11

I'm wondering if there is any capability to re-throw an existing exception (in a catch clause), within an expression switch case? Please take a look at the code example:

try 
{
    // Some code...
}
catch (Exception ex)
{
  return ex switch
  {
    ExceptionA => // return some value with expression.
    ExceptionB => // return some value with expression
    _ => throw ex
  }

}

The code will end with the following error:

Re-throwing caught exception changes stack information

This code is for example purposes; it's clear that a statement switch case is the obvious solution

switch (ex)
{
  case 1: ...
  case 2: ...
  default: throw;
{

CodePudding user response:

Just catch the specific Exception type:

try
{
    // Some code...
}
catch (ExceptionA exA)
{ 
    // maybe log this
    return "something"; 
}
catch (ExceptionB exB)
{ 
    // maybe log this
    return "something else"; 
}
catch (Exception ex)
{ 
    // log this
    throw; // throw keeps the original stacktrace as opposed to throw ex 
}

As you have asked how to do this with the switch, this should work as well:

try
{
    // Some code...
}
catch (Exception ex)
{
    switch(ex)
    {
        case ExceptionA exA:
            return "something";
        case ExceptionA exA:
            return "something else";
        default:
            throw;
    }
}
  •  Tags:  
  • Related