[Proposal] try if
: only execute try-catch-finally
block if a condition evaluates to true
#8125
-
Try-catch is often used in contexts that are already heavy on indentation, for example within a callback function's declaration, after an API call return, within a few nested Sometimes (often, I find), you'll also want a try-catch to only execute after a condition is met, which is yet another indentation. It could be helpful for readability & conciseness to provide an alternate syntax for try-catch, where you can provide a condition to be met before evaluating the try-catch itself. Consider the following code: if (someCondition)
{
try
{
someFunction();
}
catch (Exception e)
{
Console.WriteLine("Exception caught: " + e);
}
finally
{
someOtherFunction();
}
} Could be reduced to the following with such a feature: try if (someCondition)
{
someFunction();
}
catch (Exception e)
{
Console.WriteLine("Exception caught: " + e);
}
finally
{
someOtherFunction();
} Presumably, the In my opinion this feature seems very intuitive to use, and it also remains optional for anyone to use or ignore. I don't think there could be any unintended side-effects, though I don't know much when it comes to the actual language development. I do not think this should include any support for anything regarding I realize that there are other ways to address over-indenting in these situations, and that over-indenting can be a good indicator that a process is due for a slight re-factor. Still, I think this alternate syntax could be very helpful in terms of readability and will also help to make well-organized code even more organized/readable. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
You can already do this: if (someCondition) try
{
someFunction();
}
catch (Exception e)
{
Console.WriteLine("Exception caught: " + e);
}
finally
{
someOtherFunction();
} |
Beta Was this translation helpful? Give feedback.
You can already do this: