php try … else

后端 未结 6 1514
余生分开走
余生分开走 2021-01-07 18:50

Is there something similar in PHP to the try ... else in Python?

I need to know if the try block executed correctly as when the block executed correctly

6条回答
  •  花落未央
    2021-01-07 19:30

    I think the "else" clause is a bit limiting, unless you don't care about any exceptions thrown there (or you want to bubble those exceptions)... From my understanding of Python, it's basically the equivalent of this:

    try {
        //...Do Some Stuff Here
        try {
            // Else block code here
        } catch (Exception $e) {
            $e->elseBlock = true;
            throw $e;
        }
    } catch (Exception $e) {
        if (isset($e->elseBlock) && $e->elseBlock) {
            throw $e;
        }
        // catch block code here
    }
    

    So it's a bit more verbose (since you need to re-throw the exceptions), but it also bubbles up the stack the same as the else clause...

    Edit Or, a bit cleaner version (5.3 only)

    class ElseException extends Exception();
    
    try {
        //...Do Some Stuff Here
        try {
            // Else block code here
        } catch (Exception $e) {
            throw new ElseException('Else Clasuse Exception', 0, $e);
        }
    } catch (ElseException $e) {
        throw $e->getPrevious();
    } catch (Exception $e) {
        // catch block code here
    }
    

    Edit 2

    Re-reading your question, I think you may be overcomplicating things with an "else" block... If you're just printing (which isn't likely to throw an exception), you don't really need an else block:

    try {
        // Do Some stuff
        print "Success";
    } catch (Exception $e) {
        //Handle error here
        print "Error";
    }
    

    That code will only ever print either Success or Error... Never both (since if the print function throws the exception, it won't be actually printed... But I don't think the print CAN throw exceptions...).

提交回复
热议问题