Return statements in catch blocks

I have seen some developers use the return statement in a catch block. Why / when will this be a useful technique to use?

EDIT: in fact, I only saw the return keyword used.

thank

+5
exception-handling return catch-block
Mar 03 '10 at 17:39
source share
6 answers

public void Function () {

try { //some code here } catch { return; } 

}

upon return ;, the thread of execution jumps out of the function. This can only be done using void methods.

EDIT: you do this if you don't want to execute the rest of the function. For example, if you are executing an IO file and a read error occurs, you do not want to execute code that processes the data in this file, since you do not have it.

+1
Mar 03 '10 at 17:54
source share

There are times when you do not care about the exception, only that the Try operation failed. An example is the TryParse function, which in psedu code looks like this:

 try { //attempt conversion return true; } catch { return false; } 
+7
Mar 03 '10 at 17:42
source share

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

Example:

 public bool IsDatabaseAvailable() { try { // connect return true; } catch (Exception) { return false; } finally { // clean up } } 
+1
Mar 03 '10 at 17:43
source share

You might want to catch the error, write it down and say return false, which indicates whether the function was successful. In other situations, you may need to return some data that was computed in the try block.

+1
Mar 03 '10 at 17:44
source share

Some methods inside the .Net Framework make an exception if it does not have a good format.

A good example is int.TryParse(object value)

if your value is "10", this will throw an exception. In this case, we know this because of an incorrect conversion.

So

 try { int.TryParse(value); return true; } catch { return false; } 

There may be a function that tells us whether a string is a valid interfer.

If you use this form for this question, do not catch (Exception ex), as this makes .Net serialize the error inside an object that is slow.

It is also important to remember that even if you use return inside the catch try block, it will still execute the finally block.

So, if your cleaup code is inside, finally, donโ€™t worry that the infrastructure will invoke it.

My 2 cents. N.

+1
Mar 03 '10 at 17:47
source share

Any situation where you have an alternative if the attempt failed. An example would be checking for file for some operation

  bool IsComplete = false; try { // FileStream currentWriteableFile = File.OpenWrite(sFileLocation); } catch(Exception) { return false; } 
0
Mar 03 '10 at 17:52
source share



All Articles