0
Follow
4
View

Can I rethrow an existing exception in an expression switch case?

dxh8678 注册会员
6 days ago

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;
    }
}

About the Author

Question Info

Publish Time
6 days ago
Update Time
6 days ago