简体   繁体   中英

Understanding try catch block

I am confused about the whole try catch block. I understand if an exception is thrown it execute the catch block, however I have a question regarding using return inside the try block.

try {

    //other logic is here

    //this is in laravel and sends the user back and should stop operation
    if (foo != bar) {
       return Redirect::back()->with_message('This auction is closed.', 'error');
    }
} catch (Exception $e) {
    return $e->getMessage();
}

So my question is: is it okay to end operation inside the try block? Will I ever encounter an error where the return is ignored (or thought of as an exception?) and the code continues? Again, I'm very new to this.

Yes, that's a perfectly valid way to write that code.

The one case where your code will keep running after control exits the try or catch block is in PHP 5.5, which finally adopted the finally block from other languages, and can be used to run cleanup code that must always execute after the try block does, regardless of whether an exception got thrown.

But you're probably not using 5.5.

Yes it is ok. If for any reason Redirect::back or the with_message method raise an exception you will return the error message instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM