It is sometimes necessary to try/catch exceptions inside the "if" condition, but not the body that follows. In C#, this is really rather cumbersome, requiring locals and code that isn't entirely obvious, at a glance, as to its operation.
It is also sometimes necessary to write "switch" statements, which, unlike "if", have more than two possible outcomes, although in C# this requires the use of a fairly unpopular syntax.
Here's an idea for combining these.
Merging switch
with try/catch
First, we change the fundamental syntax of "switch" to be close to that fairly popular replacement, but without the extra curlies:
switch (condition)
case 1 { }
case 2 { }
default { }
Next, we make it possible to catch exceptions in the condition. Under the hood, this inserts an appropriate try/catch block only when at least one catch
is present:
switch (condition)
catch FileNotFoundException e { } // use "e"
catch ArgumentException { }
catch { }
case 1 { }
case 2 { }
default { }
Now we make it easier to chain several such statements akin to if/else chaining, by moving "default" one level up, and renaming it to "else":
switch (condition1)
catch FileNotFoundException { }
case 1 { }
case 2 { }
else switch (condition2)
case "abc" { }
case "def" { }
else
{ }
And so we have a switch
merged with try/catch
!
Combining with 'if'
Both switch
and if
now have else
clauses, so why not allow you to mix them as you please:
if (bool-condition1)
{ }
else if (bool-condition2)
{ }
else switch (string-expr)
catch FileNotFoundException { }
case "thing" { }
else
{ }
(thanks ach_l!)
Further improvements
Switching on a list or range of values has been proposed and can be easily incorporated:
switch (int-expression)
case 1 { }
case 2, 5 { }
case 10..50 { }
else switch (string-expression)
case "abc" { }
case "def" { }
else if (boolean-condition3)
{ }
else
{ }
In this case it could be really convenient to be able to reference the value in the condition clause. This can be easily incorporated by allowing one to declare a single variable in this clause the same way C#'s using
allows:
switch (var z = int-expression)
case 2, 5 { return z == 2 ? "two" : "five"; }
case 10..50 { return (z * 10).ToString(); }
Benefits
Among other benefits, one can now express a common error-handling scenario concisely, and yet not WTFy:
switch (bool-condition)
catch FileNotFoundException e { }
case true { }
case false { }
Would this solve any real-life coding difficulties you have encountered? Are there any tweaks you would apply to this?