I have seen some developers use the return statement in a catch block. Why/when would this be a useful technique to employ?
EDIT: I actually just saw the return keyword being used.
Thanks
public void Function() {
try
{
//some code here
}
catch
{
return;
}
}
when return; is hit, the execution flow jumps out of the function. This can only be done on void methods.
EDIT: you do this if you dont want to execute the rest of the function. For example if you are doing file IO and a read error happens, you dont want to execute code that handles processing the data in that file since you dont have it.
Some method inside the .Net Framework do throw exception when it doesn't have the good format.
A good example is the int.TryParse(object value)
if your value is "10s" it'll trow an exception. In this case we know it's because of invalid conversion.
So
try
{
int.TryParse(value);
return true;
}
catch { return false; }
Could be a function which tell us if the string is a valid interger.
If you do use that form for this matter please do not do catch (Exception ex) as doing so force the .Net to serialize the error inside the object which is kinda slow.
Also it is important to remember that even tho you use the return inside the try catch block it'll still execute the finally block.
So if your cleaup code is inside the finally don't worry the framework will make sure to call it.
My 2 cents. N.