BadMethodCallException 屬 PHP 標準庫(SPL)內建異常,繼承鏈:
BadMethodCallException extends BadFunctionCallException extends Exception
常見於框架源碼(如 Yii2):
namespace yii\base;
class InvalidCallException extends \BadMethodCallException {
public function getName() { return 'Invalid Call'; }
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post())
&& $model->validate()
&& $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', ['model' => $model]);
}
核心屬性與方法:
$message - 異常信息$code - 自定義代碼$file - 發生文件$line - 行號getTrace() - 堆疊跟蹤數組getTraceAsString() - 格式化堆疊字符串try {
$error = 'my error!';
throw new Exception($error);
} catch (Exception $e) {
echo $e->getMessage(); // my error!
}
class MyException extends Exception {
// 強制要求 message 參數
public function __construct($message, $code = 0) {
parent::__construct($message, $code);
}
// 自定義字符串輸出
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A Custom function for this type of exception\n";
}
}
throw new Exception('message', code); — throw 是語言結構非函數catch 塊,可多個捕獲不同類型Uncaught exception 致命錯誤try {
if (!filled_out($_POST)) {
throw new Exception('請完整填寫表單');
}
if (!check_email($email)) {
throw new Exception('郵箱格式不正確');
}
if (strlen($passwd) < 6) {
throw new Exception('密碼長度需大於 6 位');
}
if ($passwd !== $passwd1) {
throw new Exception('兩次密碼不一致');
}
if (strlen($username) > 16) {
throw new Exception('用戶名過長');
}
} catch (Exception $e) {
echo $e->getMessage(); // 統一輸出錯誤
}
throw,PHP 不會自動拋出(Java 會)catch 參數建議用具體子類,避免捕獲過廣getTraceAsString())而非直接輸出