try var #4683
Replies: 5 comments 21 replies
-
I think expression statements might cover this case: it's mentioned as a case here. If I'm reading it right, something like: double x = {
try
{
break GetValue();
}
catch (SomeException e)
{
// ...
}
} ... although the syntax seems to be somewhat up for grabs. |
Beta Was this translation helpful? Give feedback.
-
Or improved lambdas: Today you can write: using System;
double x = new Func<double>(() =>{
try
{
return 42;
}
catch (Exception e)
{
// ...
throw;
}
})(); But in the future (maybe csharp 10) using System;
double x = () =>{
try
{
return 42;
}
catch (Exception e)
{
// ...
throw;
}
}(); |
Beta Was this translation helpful? Give feedback.
-
The issue with all the suggestions in this thread so far is that there is no emphasis on what happens to try var x = GetValue();
catch (SomeException e)
{
// deal with exception
}
// x is not defined at this point |
Beta Was this translation helpful? Give feedback.
-
Another possibility is, and this solely applies to the case where the exception caught is irrelevant, we could set x to null if an exception is thrown. A major throwback of this would be that a returned // GetValue does not throw an exception, x would be equal to whatever it should be
try var x = GetValue();
// ThrowValue throws an exception, and y is set to null
try var y = ThrowValue(); |
Beta Was this translation helpful? Give feedback.
-
Some prior discussion here- #2734 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I find I often have a
try
block with just a function call in it, the return value of which I need outside the scope of thetry
, e.g.The only real drawbacks of the above code are explicit type declaration (I'd rather use
var
) and number of lines of code, so this suggestion is only a bit of sugar, but I wondered if something like the following would be possible:EDIT: It has been noted that in both cases
x
will be uninitialised at the point of// do something with x
ifGetValue()
throws an exception and thecatch
block doesn't assignx
. This suggestion does not attempt to address that issue.I've had a good look for this suggestion as already existing and can't find anything, but apologies if it's a duplicate.
Also, any suggestion around try-catch seems to be pretty contentious, but I'm hoping this one isn't as offensive as asking for an
On Error Resume Next
equivalent.Beta Was this translation helpful? Give feedback.
All reactions