在PHP中是否可能实现这个功能?
try {
$obj = new Clas();
if ($obj->foo) {
// how to exit from this try block?
}
// do other stuff here
} catch(Exception $e) {
}
我知道可以把其他东西放在{}
之间,但那会增加更多的缩进并且我不喜欢 :P
当然,用goto语句!
try {
$obj = new Clas();
if ($obj->foo) {
goto break_free_of_try;
}
// do other stuff here
} catch(Exception $e) {
}
break_free_of_try:
goto
来控制流程会导致代码混乱、出现错误,并给未来维护代码的人带来巨大的麻烦(即使是编写了goto
的同一个人),如果你在小函数中使用一次,那么在大函数中就会多次使用。永远不要使用goto
,即使在C语言中也没有必要使用goto
。在汇编语言中没有goto
,主要有jmp
指令,当然这就是goto
在底层所做的事情,这就是汇编和机器码的工作方式,使用跳转和调用。 - Christos Lytras其实并没有必要这样做,但你可以在try
块中强制产生一个异常来停止函数的执行,体验一下这种乐趣。
try {
if ($you_dont_like_something){
throw new Exception();
//No code will be executed after the exception has been thrown.
}
} catch (Exception $e){
echo "Something went wrong";
}
我也遇到了这种情况,和你一样,不希望有无数的if/else if/else if/else语句,因为这样会使代码难以阅读。
最终我扩展了Exception类来实现我的需求。下面是一个示例类,用于处理验证问题,如果触发,则会产生较轻微的“日志通知”。
class ValidationEx extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
在我的主代码中,我调用它;
throw new ValidationEx('You maniac!');
catch(ValidationEx $e) { echo $e->getMessage(); }
catch(Exception $e){ echo $e->getMessage(); }
欢迎提出意见和批评,我们在这里都是为了学习!
catch(Exception $e){ echo $e->getMessage(); }
就可以达到同样的效果了。 - Your Common Sensetry{
$obj = new Clas();
if(!$obj->foo){
// do other stuff here
}
}catch(Exception $e){
}
try
{
$object = new Something();
if ($object->value)
{
// do stuff
}
else
{
// do other stuff
}
}
catch (Exception $e)
{
// handle exceptions
}
class OtherException extends Exception
{
//...
}
if ($e instanceof OtherException)
来捕获特定的异常,或者在catch \Exception
块中决定如何处理异常。
try {
$obj = (object) array('foo' => 'bar');
if ($obj->foo) {
throw new OtherException;
}
/* do stuff */
} catch (OtherException $e) {
/* do other stuff here and handle exception */
} catch (Exception $e) {
if ($e instanceof InvalidArgumentException) {
throw $e; //don't handle the exception
}
}
<?php
echo 'this' . PHP_EOL;
switch(true) {
default:
try {
echo 'is' . PHP_EOL;
break;
echo 'not' . PHP_EOL;
} catch (Exception $e) {
// error_log($e->getMessage());
}
}
echo 'fun !';
:-)
throw new MyException("optional message", MyException::ERROR_SUCCESS);
我显然通过使用这段代码(在catch()
语句内部)捕获到了它
catch(MyException $e) {
switch($e->getCode()) {
/** other cases make sense here */
case MyException::ERROR_SQL:
logThis("A SQL error occurred. Details: " . $e->getMessage());
break;
case MyException::ERROR_SUCCESS:
logThis("Completed with success. Details: " . $e->getMessage());
break;
case MyException::ERROR_UNDEFINED:
default:
logThis("Undefined error. Details: " . $e->getMessage());
break;
}
}
MyException
只是Exception的一个扩展,它还定义了类常量。
throw('Get me out of here!')
会跳出程序,但这样做不太友好。 - Marc B