Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to execute code outside of try block only if no exception is thrown

This question is about the best way to execute code outside of try block only if no exception is thrown.

try {
    //experiment
    //can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
    //contain the blast
} finally {
    //cleanup
    //this is not the answer since it executes even if an exception occured
    //finally will be available in php 5.5
} else {
    //code to be executed only if no exception was thrown
    //but no try ... else block exists in php
}

This is method suggested by @webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.

$caught = false;

try {
    // something
} catch (Exception $e) {
    $caught = true;
}

if (!$caught) {

}

So what is a better (or the best) way to accomplish this without the need for an extra variable?

like image 495
km6zla Avatar asked Jun 12 '13 19:06

km6zla


People also ask

What will happen if no exception is thrown in the try block?

What happens if no exception is thrown in a try block? All statements are executed in try block if no exception is occurs and ignores catch blocks and execution resumes after catch block. So, if no exception is thrown in try block, all catch blocks are ignored and execution continues after the catch blocks.

Does finally execute if no exception is thrown?

A finally block always executes, regardless of whether an exception is thrown.

Which block executes with without exception?

Else Clause Example: Else block will execute only when no exception occurs.

How do you handle exceptions without try and catch?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.


1 Answers

One possibility is to put the try block in a method, and return false if an exception is cought.

function myFunction() {
    try {
        // Code  that throws an exception
    } catch(Exception $e) {
        return false;
    }
    return true;
}
like image 107
rcapote Avatar answered Oct 26 '22 04:10

rcapote