2

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(); } 
3
  • 1
    Are you getting an error message on the if version? Im pretty sure the ternary is not legal C#; ternaries are expressions, not statements Commented Dec 22, 2021 at 3:28
  • Do you mean the if in the first example? if so, no, that works fine. Commented Dec 22, 2021 at 3:30
  • @Flydog57 throw someException is legal in a ternary, but throw is not, this is from C#7 stackoverflow.com/questions/42209135/… Commented Dec 22, 2021 at 4:02

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Good catch.
Thanks, that makes sense. For sake of completeness, would it be correct to assume that your suggestion implies that re-throwing an exception in the pattern I wrote in the first block, is not possible in a conditional expression?
@Hamed No, you certainly can rethrow it. For example: catch (Exception e) when (someCondition) { throw; } would work fine, as would more complicated logic in the catch.
Actually, I meant in a pattern like condition ? throw : anotherException(). Though I agree your suggested approach is more clear/readble.
I believe the throw part alone in a ternary expression isn't valid C#.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.