在PHP中冒泡异常?

时间:2010-11-21 19:29:51

标签: php exception

我正在用PHP制作简单的纸牌游戏。当用户尝试播放卡片时,如果可以/不可以,我想抛出异常。而不是返回具有特定含义的数字(例如1代表坏卡,2代表不是你的转...等等),我想使用自定义异常。我会捕获这些异常并将消息显示给用户。

我意识到异常是出于异常错误的意思,但我认为这是设计程序的好方法。

问题:我的例外情况未被捕获。我有一个名为play.php的页面,它控制一个名为Game的类,它有一个抛出异常的Round。 play.php页面从游戏中获取回合,并对其进行函数调用。但是,它说这个例外没有全面发现。

有快速解决方法吗?如何将Round类中的异常冒泡到play.php页面?

// in PLAY.php
try {
    $game->round->startRound($game->players);
} catch (RoundAlreadyStartedException $e) {
    echo $e->getMessage();
}

// in ROUND class
        if (!($this->plays % (self::PLAYS_PER_ROUND + $this->dealer))) {
            try {
                throw new RoundAlreadyStartedException();
            } catch (RoundAlreadyStartedException $e) {
                throw $e;
            }
            return;
        }

我试过捕捉,不捕捉,投掷,重新抛弃等等。

3 个答案:

答案 0 :(得分:6)

我同意一些评论,这是实现你想做的奇怪方法,但是我看不到任何实际的代码问题。我的测试用例:

class TestException extends Exception {
}

function raiseTestException() {
    try {
        throw new TestException("Test Exception raised");
    } catch(TestException $e) {
        throw $e;
    }
    return;
}

try {
    raiseTestException();
} catch(TestException $e) {
    echo "Error: " . $e->getMessage();
}

// result: "Error: Test Exception raised";

它实际上是RoundAlreadyStartedException没有被捕获,还是其他一些错误?

编辑:包装在课堂上,因为它有可能产生影响(它没有):

class TestException extends Exception {
}

class TestClass {

    function raiseTestException() {
        try {
            throw new TestException("Test Exception raised");
        } catch(TestException $e) {
            throw $e;
        }
        return;
    }

}

class CallerClass {

    function callTestCallMethod() {
        $test = new TestClass();
        try {
            $test->raiseTestException();
        } catch(TestException $e) {
            echo "Error: " . $e->getMessage();
        }
    }

}

$caller = new CallerClass();
$caller->callTestCallMethod();

// result: "Error: Test Exception raised";

答案 1 :(得分:3)

我有同样的奇怪行为,但没有冒泡的例外。 事实证明,我在另一个命名空间中有例外,但我并没有明确地使用它,PHP并没有抱怨这一点。 因此,添加using mynamespace\exceptions\MyException;解决了它。 也许这也可能发生在你身上。

HTH。

答案 2 :(得分:1)

我在Laravel 4.2中遇到同样的问题

当Laravel监听\ Exception处理程序时,你不能使用root来抛出异常并期望在应用程序中冒泡,除非你修改或扩展Laravel。你需要的是创建一个空的Exception,它扩展了你的命名空间的\ Exception,然后捕获你的命名空间Exception,如何你需要。

<?php
namespace Yournamespacehere;

class Exception extends \Exception {
}