开发者

Return statements in catch blocks

I have s开发者_如何转开发een 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.


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;
}


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 don't want to execute the rest of the function. For example, if you are doing file IO and a read error happens, you don't want to execute code that handles processing the data in that file since you don't have it.


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
    }
}


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


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.


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;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜