throw

(PHP 5, PHP 7, PHP 8)

throw キーワードは式であり、式を書ける場所ならどこでも使えます。 引数として Throwable オブジェクトを受け取ります。

警告

PHP 8.0.0 より前のバージョンでは、throw キーワードは式ではなく文でした。

Throwable ではないオブジェクトを throw しようとすると、 Error がスローされます。

例1 Throwable ではないオブジェクトをスローする

<?php
throw new class {};

上の例の出力は、 たとえば以下のようになります。

PHP Fatal error:  Uncaught Error: Cannot throw objects that do not implement Throwable in Command line code:1
Stack trace:
#0 {main}

throw を使うと通常の処理の流れは中断され、 スローされたオブジェクトが catch ブロックでキャッチされるか、グローバルスコープに達するまで、 コールスタックが巻き戻されます。 後者の場合、プログラムは致命的なエラーで終了します。 このエラーには、Throwable オブジェクトがスローされた場所を示すスタックトレースが含まれます。

例2 グローバルスコープで例外をスローする

<?php
echo "Before exception\n";
throw new Exception('Stop execution');
echo "After exception\n";

上の例の出力は、 たとえば以下のようになります。

Before exception
PHP Fatal error:  Uncaught Exception: Stop execution in Command line code:2
Stack trace:
#0 {main}
  thrown in Command line code on line 2

例3 関数内で例外をスローする

<?php

function foo() {
    echo "Before exception\n";
    throw new Exception('Stop execution');
    echo "After exception\n";
}

foo();

上の例の出力は、 たとえば以下のようになります。

Before exception
PHP Fatal error:  Uncaught Exception: Stop execution in Command line code:3
Stack trace:
#0 Command line code(7): foo()
#1 {main}
  thrown in Command line code on line 3

throw は式なので、別の式の結果が不適切な値だった場合に、 処理を分岐させるのに使えます。

例4 throw を式として使う

PHP 8.0.0 以降でのみ許されます。

<?php

function test() {
    do_something_risky() or throw new Exception('It did not work');
}

function do_something_risky() {
    return false; // 失敗をシミュレートする
}

try {
    test();
} catch (Exception $e) {
    print $e->getMessage();
}

上の例の出力は以下となります。

It did not work

スローされた Throwable は、 try-catch ブロックで処理できます。 詳細は エラー処理 を参照ください。

+add a note

User Contributed Notes

There are no user contributed notes for this page.