Exceptionクラス
クラス Exception は、PHPにおけるすべての例外の基底クラスです。
エラーメッセージの取得、エラーコード、例外が発生したファイルと行、
および呼び出しスタックを扱うための基本的なメソッドを含んでいます。
例外を作成する際には、メッセージ、エラーコード、および以前の例外を渡すことができます。
構文
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
例
シンプルな例外を作成して処理します:
<?php
try {
throw new Exception('Something went wrong', 100);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
コード実行結果:
'Error: Something went wrong'
例
Exceptionクラスの主要なメソッドを使用します:
<?php
try {
throw new Exception('Test exception', 123);
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage() . "\n";
echo 'Code: ' . $e->getCode() . "\n";
echo 'File: ' . $e->getFile() . "\n";
echo 'Line: ' . $e->getLine() . "\n";
}
?>
コード実行結果(例):
'Message: Test exception
Code: 123
File: /path/to/file.php
Line: 3'
例
例外発生時の呼び出しスタックを取得します:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
コード実行結果(例):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
関連項目
-
クラス
ErrorException,
エラーを例外として表現します -
関数
set_exception_handler,
ユーザー定義の例外ハンドラを設定します