.netexceptionreturncatch-block

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.


Solution

  • 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.