【发布时间】:2011-05-13 11:53:53
【问题描述】:
我正在用 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;
}
我试过接,不接,扔,再扔等等。
【问题讨论】:
-
这听起来很糟糕。
-
我来自 Java 背景 :)
-
如果不看任何代码就很难诊断。
-
你在使用
try ... catch块吗? -
I realize that exceptions are meant for out of the ordinary errors, but I think this is a good way to design my program.我想我不同意你的观点;)。普通的 ol' 返回值有什么问题?