PHPでカスタマイズされた例外の対処方法

PHPのカスタム例外を処理するには、以下の手順に従ってください。

  1. 独自の例外クラスを作成し、組み込みの例外クラスから継承します。実際のニーズに応じてカスタムの例外処理ロジックを追加できます。
class CustomException 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";
  }
}
  1. 投げる
  2. 投げる
throw new CustomException("自定义异常消息", 1001);
  1. 例外処理
  2. キャッチ
try {
  // 可能会抛出自定义异常的代码
} catch (CustomException $e) {
  // 捕获并处理自定义异常
  echo $e->getMessage();
  echo $e->getCode();
}

これら手順を実施すると、カスタム例外処理機能を実現できます。例外をスローすると、カスタム例外メッセージと例外コードを提供できます。例外を捕捉すると、捕獲された例外を必要に応じて処理できます。

bannerAds