php尝试...其他

Pwn*_*nna 18 php exception

PHP中有类似于try ... elsePython的东西吗?

我需要知道try块是否正确执行,因为块正确执行时,将打印一条消息.

web*_*ave 48

PHP没有try/catch/else.但是,您可以在catch块中设置一个可用于确定它是否已运行的变量:

$caught = false;

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

if (!$caught) {

}
Run Code Online (Sandbox Code Playgroud)

  • 一个小注意,python的else块只会在`$ caught`为false时执行,不是真的...... (2认同)

irc*_*ell 5

我认为"else"子句有点限制,除非你不关心那里抛出的任何异常(或者你想要冒泡那些异常)......从我对Python的理解,它基本上相当于:

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
}
Run Code Online (Sandbox Code Playgroud)

所以它有点冗长(因为你需要重新抛出异常),但它也会像使用else子句一样冒泡堆栈...

编辑或者,更清洁的版本(仅限5.3)

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
}
Run Code Online (Sandbox Code Playgroud)

编辑2

重新阅读你的问题,我认为你可能用"else"块过度复杂化了......如果你只是打印(不太可能抛出异常),你真的不需要一个else块:

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

该代码将只打印要么 SuccessError...从来都(因为如果print函数抛出异常,也不会被实际打印...但我不认为print可以抛出异常......).


Mva*_*est -2

您可以使用try { } catch () { }throw。请参阅http://php.net/manual/en/language.exceptions.php

try {
    $a = 13/0; // should throw exception
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
Run Code Online (Sandbox Code Playgroud)

或手动:

try {
    throw new Exception("I don't want to be tried!");
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 我没有投反对票,但他问的是“else”块,而不是一般的例外...... (2认同)