Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statements in catch blocks

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

like image 753
GurdeepS Avatar asked Mar 03 '10 17:03

GurdeepS


2 Answers

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;
}
like image 111
Thomas Avatar answered Oct 03 '22 09:10

Thomas


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.

like image 41
Jonathan S. Avatar answered Oct 03 '22 07:10

Jonathan S.