Return statements in catch blocks

2019-02-17 22:34发布

问题:

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

回答1:

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.



回答2:

There are occasions when you do not care about the exception thrown, only that the Try operation failed. An example would be the TryParse functions which in pseduo code look like:

try
{
   //attempt conversion
   return true;
}
catch
{
   return false;
}


回答3:

This would be useful if you know what the return value of the function should be in the catch block.

Example:

public bool IsDatabaseAvailable() {
    try {
        // connect
        return true;
    }
    catch (Exception) {
        return false;
    }
    finally {
        // clean up
    }
}


回答4:

You might want to catch the error, log it and say return a value of false which indicates if the function was successful. In other situations you might want to return some data which was calculated in the try block



回答5:

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.



回答6:

Any situation where you have an alternative if the attempt fails. An example could be checking if file is available for some operation

    bool IsComplete = false;

    try
    {
      //  FileStream currentWriteableFile = 
                     File.OpenWrite(sFileLocation);          
    }
    catch(Exception)
    {
      return false;
    }