Home > Enterprise >  Re-throw an exception in a conditional expression
Re-throw an exception in a conditional expression

Time:12-22

What is the correct way of rewriting the code in the following catch block using a conditional expression? if supported!?

try
{
    return await _client.GetStreamAsync(_uri);
}
catch
{                
    if (IsConnected)
        throw;
    else
        throw new IOException();
}

C# compiler does not like the following

IsConnected ? throw : new IOException();

Note that re-throwing a caught exception, like the following, is in violation of CA2200

try
{
    return await _client.GetStreamAsync(_uri);
}
catch (Exception ex)
{
    throw IsConnected ? throw ex : new IOException();
}

CodePudding user response:

Your first example is fine. throw; will rethrow the exception leaving the stack trace in tact. As an alternative, I would suggest just conditionally catching the exception when IsConnected == false:

catch when (IsConnected)
{
    throw new IOException();
}

You can read more about the when keyword in the docs.

  • Related