PHP 5.4.31 Released

Exception::getCode

(PHP 5 >= 5.1.0)

Exception::getCode例外コードを取得する

説明

final public mixed Exception::getCode ( void )

例外コードを返します。

パラメータ

この関数にはパラメータはありません。

返り値

例外コードを整数値で返します。しかし、 Exception クラスを継承したクラスでは、違う型を返すこともあります (たとえば PDOException は文字列を返します)。

例1 Exception::getCode() の例

<?php
try {
    throw new 
Exception("Some error message"30);
} catch(
Exception $e) {
    echo 
"The exception code is: " $e->getCode();
}
?>

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

The exception code is: 30

add a note add a note

User Contributed Notes 2 notes

up
8
talksonweb at gmail dot com
1 year ago
The exception code can be used to categorize your errors. If you're wondering what the exception code can be used for, read on below.

Let's say each time your application isn't able to connect to the database, you can save the error message under the error/exception code 214. At the end of the month, you can do a quick search on the error number '214' and find out how many times this error occurred. This makes life easier. Also, the error/exception message will give you details into what happened.

The point is to use both the exception message and code. It's helpful in the long run.

Note: I added this note, because I was confused earlier as to the purpose of the exception code and it's use.
up
3
ricky at rocker dot com
1 year ago
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0

<?php
try {
  throw new
Exception("no code!!");
} catch (
Exception $e) {
  print(
"Code='" . $e->getCode() . "'");
}
?>

outputs

Code='0'
To Top