(PHP 7, PHP 
Введение
Error — базовый класс
для всех внутренних ошибок PHP.
Обзор классов
Свойства
- message
-
Сообщение об ошибке
- code
-
Код ошибки
- file
-
Имя файла, в котором произошла ошибка
- line
-
Номер строки, в которой произошла ошибка
- previous
-
Ранее выброшенное исключение
- string
-
Строковое представление трассировки стека
- trace
-
Трассировка стека в виде массива
Содержание
- Error::__construct — Создаёт объект класса Error
- Error::getMessage — Получает сообщение об ошибке
- Error::getPrevious — Возвращает предыдущий Throwable
- Error::getCode — Возвращает код ошибки
- Error::getFile — Получает файл, в котором произошла ошибка
- Error::getLine — Получает номер строки, в которой произошла ошибка
- Error::getTrace — Получает трассировку стека
- Error::getTraceAsString — Получает трассировку стека в виде строки
- Error::__toString — Строковое представление ошибки
- Error::__clone — Клонирует ошибку
whysteepy at gmail dot com ¶
5 years ago
Lists of Throwable and Exception tree as of 7.2.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
ArgumentCountError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/sDMsv
posted here http://php.net/manual/en/class.throwable.php
dams at php dot net ¶
1 year ago
Lists of Throwable and Exception tree as of 8.1.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
CompileError
ParseError
FiberError
TypeError
ArgumentCountError
UnhandledMatchError
ValueError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
JsonException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/f8Boe
Initially posted by whysteepy at gmail dot com for PHP 7.2.0, based on the gist
JustinasMalkas ¶
7 years ago
If after PHP upgrade you're getting error "PHP Fatal error: Cannot declare class error, because the name is already in use ...", you will have to rename your "error" class.
Since PHP 7 classname "Error" is predefined and used internally.
Содержание
- Error
- Введение
- Обзор классов
- Свойства
- Содержание
- User Contributed Notes 3 notes
- Правильная обработка ошибок в PHP
- Универсальное решение
- Форматы вывода
- Логирование
- Trace
- И самое полезное… ссылки на открытие файлов в IDE прямо из trace.
- PHP Error Handling
- PHP Error Handling
- Basic Error Handling: Using the die() function
- Example
- Example
- Creating a Custom Error Handler
- Syntax
- Error Report levels
- Set Error Handler
- Example
- Trigger an Error
- Example
- Example
- Error Logging
- Send an Error Message by E-Mail
- ErrorException
- Введение
- Обзор классов
- Свойства
- Примеры
- Содержание
- User Contributed Notes 6 notes
Error
Введение
Error — базовый класс для всех внутренних ошибок PHP.
Обзор классов
Свойства
Сообщение об ошибке
Имя файла, в котором произошла ошибка
Номер строки, в которой произошла ошибка
Ранее выброшенное исключение
Строковое представление трассировки стека
Трассировка стека в виде массива
Содержание
- Error::__construct — Создаёт объект класса Error
- Error::getMessage — Получает сообщение об ошибке
- Error::getPrevious — Возвращает предыдущий Throwable
- Error::getCode — Возвращает код ошибки
- Error::getFile — Получает файл, в котором произошла ошибка
- Error::getLine — Получает номер строки, в которой произошла ошибка
- Error::getTrace — Получает трассировку стека
- Error::getTraceAsString — Получает трассировку стека в виде строки
- Error::__toString — Строковое представление ошибки
- Error::__clone — Клонирует ошибку
User Contributed Notes 3 notes
Lists of Throwable and Exception tree as of 7.2.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
ArgumentCountError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Lists of Throwable and Exception tree as of 8.1.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
CompileError
ParseError
FiberError
TypeError
ArgumentCountError
UnhandledMatchError
ValueError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
JsonException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Initially posted by whysteepy at gmail dot com for PHP 7.2.0, based on the gist
Источник
Правильная обработка ошибок в PHP
Универсальное решение
- require ‘exceptionHandler/exceptionHandlerClass.php’ ;
- exceptionHandlerClass :: setupHandlers ( ) ;
Форматы вывода
- public function getExceptionHandlerOutput ( ) <
- if ( php_sapi_name ( ) == ‘cli’ ) <
- return new exceptionHandlerOutputCli ( ) ;
- >
- return new exceptionHandlerOutputWeb ( ) ;
- >
- exceptionHandlerClass :: setupHandlers ( new exceptionHandlerOutputAjax ( ) ) ;
- class exceptionHandlerOutputAjax extends exceptionHandlerOutput <
- public function output ( $exception , $debug ) <
- header ( ‘HTTP/1.0 500 Internal Server Error’ , true , 500 ) ;
- header ( ‘Status: 500 Internal Server Error’ , true , 500 ) ;
- $response = array (
- ‘error’ => true ,
- ‘message’ => » ,
- ) ;
- if ( $debug ) <
- $response [ ‘message’ ] = $exception -> getMessage ( ) ;
- > else <
- $response [ ‘message’ ] = self :: $productionMessage ;
- >
- exit ( json_encode ( $response ) ) ;
- >
- >
- class exceptionHandlerOutputAjaxFactory extends exceptionHandlerOutputDefaultFactory <
- public function getExceptionHandlerOutput ( ) <
- if ( self :: detect ( ) ) <
- return new exceptionHandlerOutputAjax ( ) ;
- >
- parent :: getExceptionHandlerOutput ( ) ;
- >
- public static function detect ( ) <
- return ( ! empty ( $_SERVER [ ‘HTTP_X_REQUESTED_WITH’ ] )
- && strtolower ( $_SERVER [ ‘HTTP_X_REQUESTED_WITH’ ] ) == ‘xmlhttprequest’ ) ;
- >
- >
- exceptionHandlerClass :: setupHandlers ( new exceptionHandlerOutputAjaxFactory ( ) ) ;
Логирование
- public static function exceptionLog ( $exception , $logPriority = null ) <
- if ( ! is_null ( self :: $exceptionHandlerLog ) ) <
- self :: $exceptionHandlerLog -> log ( $exception , $logPriority ) ;
- >
- >
- exceptionHandlerClass :: $exceptionHandlerLog = new exceptionHandlerSimpleLog ( ) ;
- class exceptionHandlerSimpleLog extends exceptionHandlerLog <
- public function log ( $exception , $logType ) <
- switch ( $logType ) <
- case self :: uncaughtException :
- error_log ( $exception -> getMessage ( ) ) ;
- break ;
- >
- >
- >
- const uncaughtException = 0 ; //необработанные исключения
- const caughtException = 1 ; //вызов метода логирования вне обработчиков ошибок
- const ignoredError = 2 ; //ошибки маскированные @, логируются если выключена опция scream
- const lowPriorityError = 3 ; //ошибки которые не превращаются exception
- const assertion = 4 ; //assertion
Имея logType и exception разработчик может сам решить какие искллючения и как логировать. Например, uncaughtException можно высылать по почте, ignoredError с severity E_ERROR логировать в файл итп.
Trace
И самое полезное… ссылки на открытие файлов в IDE прямо из trace.
- exceptionHandlerOutputCli :: setFileLinkFormat ( ‘: in %f on line %l’ ) ;
Можно реализовать для NetbBeans (или другого IDE). Для этого нужно: зарегистрировать протокол; сделать обработчик этого протокола (самое простое — bat файл). В обработчике через командную строку вызвать NetBeans с соответствующим файлом и строкой. Но это тема для следующей статьи.
Код писался за два дня так, что возможны мелкие недочеты. Скачать (не было времени, чтобы выложить в репозиторий).
UPD: перенесено в блог PHP
UPD2: в продолжение темы работа с исключениями в PHP
Источник
PHP Error Handling
Error handling in PHP is simple. An error message with filename, line number and a message describing the error is sent to the browser.
PHP Error Handling
When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
This tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods:
- Simple «die()» statements
- Custom errors and error triggers
- Error reporting
Basic Error Handling: Using the die() function
The first example shows a simple script that opens a text file:
Example
If the file does not exist you might get an error like this:
To prevent the user from getting an error message like the one above, we test whether the file exist before we try to access it:
Example
Now if the file does not exist you get an error like this:
The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. Let’s take a look at alternative PHP functions for handling errors.
Creating a Custom Error Handler
Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):
Syntax
| Parameter | Description |
|---|---|
| error_level | Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels |
| error_message | Required. Specifies the error message for the user-defined error |
| error_file | Optional. Specifies the filename in which the error occurred |
| error_line | Optional. Specifies the line number in which the error occurred |
| error_context | Optional. Specifies an array containing every variable, and their values, in use when the error occurred |
Error Report levels
These error report levels are the different types of error the user-defined error handler can be used for:
| Value | Constant | Description |
|---|---|---|
| 1 | E_ERROR | A fatal run-time error. Execution of the script is stopped |
| 2 | E_WARNING | A non-fatal run-time error. Execution of the script is not stopped |
| 8 | E_NOTICE | A run-time notice. The script found something that might be an error, but could also happen when running a script normally |
| 256 | E_USER_ERROR | A fatal user-generated error. This is like an E_ERROR, except it is generated by the PHP script using the function trigger_error() |
| 512 | E_USER_WARNING | A non-fatal user-generated warning. This is like an E_WARNING, except it is generated by the PHP script using the function trigger_error() |
| 1024 | E_USER_NOTICE | A user-generated notice. This is like an E_NOTICE, except it is generated by the PHP script using the function trigger_error() |
| 2048 | E_STRICT | Not strictly an error. |
| 8191 | E_ALL | All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4) |
Now lets create a function to handle errors:
The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
Now that we have created an error handling function we need to decide when it should be triggered.
Set Error Handler
The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script.
It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors:
Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
Example
Testing the error handler by trying to output variable that does not exist:
The output of the code above should be something like this:
Trigger an Error
In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.
Example
In this example an error occurs if the «test» variable is bigger than «1»:
The output of the code above should be something like this:
An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
Possible error types:
- E_USER_ERROR — Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
- E_USER_WARNING — Non-fatal user-generated run-time warning. Execution of the script is not halted
- E_USER_NOTICE — Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
Example
In this example an E_USER_WARNING occurs if the «test» variable is bigger than «1». If an E_USER_WARNING occurs we will use our custom error handler and end the script:
The output of the code above should be something like this:
Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.
Error Logging
By default, PHP sends an error log to the server’s logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.
Sending error messages to yourself by e-mail can be a good way of getting notified of specific errors.
Send an Error Message by E-Mail
In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
The output of the code above should be something like this:
And the mail received from the code above looks like this:
This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.
Источник
ErrorException
(PHP 5 >= 5.1.0, PHP 7, PHP 
Введение
Исключение в случае возникновения ошибки.
Обзор классов
Свойства
Примеры
Пример #1 Использование set_error_handler() для изменения сообщений об ошибках в ErrorException.
function exception_error_handler ( $severity , $message , $file , $line ) <
if (!( error_reporting () & $severity )) <
// Этот код ошибки не входит в error_reporting
return;
>
throw new ErrorException ( $message , 0 , $severity , $file , $line );
>
set_error_handler ( «exception_error_handler» );
/* вызываем исключение */
strpos ();
?>
Результатом выполнения данного примера будет что-то подобное:
Содержание
- ErrorException::__construct — Создаёт исключение
- ErrorException::getSeverity — Получает серьёзность исключения
User Contributed Notes 6 notes
As noted below, it’s important to realize that unless caught, any Exception thrown will halt the script. So converting EVERY notice, warning, or error to an ErrorException will halt your script when something harmlesss like E_USER_NOTICE is triggered.
It seems to me the best use of the ErrorException class is something like this:
function custom_error_handler ( $number , $string , $file , $line , $context )
<
// Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
$error_is_enabled = (bool)( $number & ini_get ( ‘error_reporting’ ) );
// — FATAL ERROR
// throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
if( in_array ( $number , array( E_USER_ERROR , E_RECOVERABLE_ERROR )) && $error_is_enabled ) <
throw new ErrorException ( $errstr , 0 , $errno , $errfile , $errline );
>
// — NON-FATAL ERROR/WARNING/NOTICE
// Log the error if it’s enabled, otherwise just ignore it
else if( $error_is_enabled ) <
error_log ( $string , 0 );
return false ; // Make sure this ends up in $php_errormsg, if appropriate
>
>
?>
Setting this function as the error handler will result in ErrorExceptions only being thrown for E_USER_ERROR and E_RECOVERABLE_ERROR, while other enabled error types will simply get error_log()’ed.
It’s worth noting again that no matter what you do, «E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT» will never reach your custom error handler, and therefore will not be converted into ErrorExceptions. Plan accordingly.
E_USER_WARNING, E_USER_NOTICE, and any other non-terminating error codes, are useless and act like E_USER_ERROR (which terminate) when you combine a custom ERROR_HANDLER with ErrorException and do not CATCH the error. There is NO way to return execution to the parent scope in the EXCEPTION_HANDLER.
( E_ALL );
define ( ‘DEBUG’ , true );
define ( ‘LINEBREAK’ , «rn» );
error :: initiate ( ‘./error_backtrace.log’ );
try
trigger_error ( «First error» , E_USER_NOTICE );
catch ( ErrorException $e )
print( «Caught the error: » . $e -> getMessage . «
rn» );
trigger_error ( «This event WILL fire» , E_USER_NOTICE );
trigger_error ( «This event will NOT fire» , E_USER_NOTICE );
abstract class error <
public static $LIST = array();
private function __construct () <>
public static function initiate ( $log = false ) <
set_error_handler ( ‘error::err_handler’ );
set_exception_handler ( ‘error::exc_handler’ );
if ( $log !== false ) <
if ( ! ini_get ( ‘log_errors’ ) )
ini_set ( ‘log_errors’ , true );
if ( ! ini_get ( ‘error_log’ ) )
ini_set ( ‘error_log’ , $log );
>
>
public static function err_handler ( $errno , $errstr , $errfile , $errline , $errcontext ) <
$l = error_reporting ();
if ( $l & $errno ) <
$exit = false ;
switch ( $errno ) <
case E_USER_ERROR :
$type = ‘Fatal Error’ ;
$exit = true ;
break;
case E_USER_WARNING :
case E_WARNING :
$type = ‘Warning’ ;
break;
case E_USER_NOTICE :
case E_NOTICE :
case @ E_STRICT :
$type = ‘Notice’ ;
break;
case @ E_RECOVERABLE_ERROR :
$type = ‘Catchable’ ;
break;
default:
$type = ‘Unknown Error’ ;
$exit = true ;
break;
>
$exception = new ErrorException ( $type . ‘: ‘ . $errstr , 0 , $errno , $errfile , $errline );
if ( $exit ) <
exc_handler ( $exception );
exit();
>
else
throw $exception ;
>
return false ;
>
function exc_handler ( $exception ) <
$log = $exception -> getMessage () . «n» . $exception -> getTraceAsString () . LINEBREAK ;
if ( ini_get ( ‘log_errors’ ) )
error_log ( $log , 0 );
print( «Unhandled Exception» . ( DEBUG ? » — $log » : » ));
>
To add to the comments made by chris AT cmbuckley DOT co DOT uk about the ErrorException problem with args:
I noticed that the problem is in the ErrorException class itself, not the Exception class. When using just the exception class, it’s no longer an issue. Besides the args problem, the only difference between Exception and ErrorException in the stack trace is that the args are left out of the error handler exception function. I’m not sure if this was on purpose or not, but it shouldn’t hurt to show this information anyway.
So instead of using this broken extended class, you can ignore it and make your own extended class and avoid the problem all together:
class ErrorHandler extends Exception <
protected $severity ;
public function __construct ( $message , $code , $severity , $filename , $lineno ) <
$this -> message = $message ;
$this -> code = $code ;
$this -> severity = $severity ;
$this -> file = $filename ;
$this -> line = $lineno ;
>
public function getSeverity () <
return $this -> severity ;
>
>
function exception_error_handler ( $errno , $errstr , $errfile , $errline ) <
throw new ErrorHandler ( $errstr , 0 , $errno , $errfile , $errline );
>
set_error_handler ( «exception_error_handler» , E_ALL );
function A () <
$foo -> bar ; // Purposely cause error
>
try <
B ( ‘foobar’ );
> catch ( Exception $e ) <
var_dump ( $e -> getTrace ());
>
?>
The only thing I wish I could do was remove the entry for the error handler function because it’s quite irrelevant. Maybe that’s what they were trying to do with the ErrorException class? Either way, you can’t change it because the trace functions are final, and the variable is private.
Going on further from the point made by triplepoint at gmail dot com:
I’m using PHP 7.4.0 and trying to introduce error handling, exception handling and fatal exception handling into my application. A lot of the info all over the internet is now out of date in regards to handling errors with the new changes in PHP 7 and 8, which makes it difficult at the best of times to understand everything.
However what I’ve found is that by using register_shutdown_function to handle fatal exceptions, it works as expected. set_exception_handler also works perfectly in conjunction. The issue comes when you use set_error_handler as well, and you trigger a custom error (for example using trigger_error) — even if you’re using E_ERROR or E_USER_ERROR.
This is because PHP is trying to handle the error before it shuts down and before the register_shutdown_function is actually involved. So it’s very important to be mindful of this if you’re using different methods for exceptions, errors and fatal exceptions. You will need to specifically catch the error like before and return out of your error handling function for the fatal exception handler to kick in properly.
/**
* We handle basic errors differently to everything else
*/
public static function errorHandler ( $errStatus , $errMsg = ‘Unknown error’ , $errFile = ‘unknown’ , $errLine = 0 )
<
/**
* Because we’re using set_error_handler, PHP tries to be
* clever and routes fatal errors and other «errors»
* (i.e. trigger_error) here before it goes to
* register_shutdown_function, so we need to be sure these
* are caught and dealt with in the correct way
*
* @See https://www.php.net/manual/en/class.errorexception.php#95415
*/
if ( in_array ( $errStatus , [ E_ERROR , E_PARSE , E_CORE_ERROR , E_USER_ERROR , E_ERROR ]))
<
return;
>
/* Handle everything else however you want */
>
I have been Googling all over the place for how to convert an E_NOTICE error into an exception, and I think I finally found a clean way to do it:
$lastError = error_get_last();
if ( !empty( $lastError ) ) <
throw new TemplateRenderingException($lastError[‘message’], $lastError[‘type’]);
>
Basically, if it’s something not system haulting it will likely hit this. Then you can throw whatever exception you want. Now, this is of course if you have a need. I did, because I wanted to clean up my output buffer if there was an error that skipped over it.
function exception_error_handler ( $errno , $errstr , $errfile , $errline ) <
throw new ErrorException ( $errstr , $errno , 0 , $errfile , $errline );
>
set_error_handler ( «exception_error_handler» );
/* Trigger exception */
strpos ();
?>
Please note that property $severity of class ErrorException is set to a constant zero for all kinds of errors in the above example.
I think it was a bug and tried to file a bug report, but it was closed as not a bug, so I could not say the above is wrong.
Let me show an example that uses $severity not as a constant:
(function ( $errno , $errstr , $errfile , $errline ) <
throw new ErrorException ( $errstr , 0 , $errno , $errfile , $errline );
>);
class MyClass <
public function methodA () <
echo( «methodA:n» );
strpos ();
>
public function methodB () <
echo( «methodB:n» );
trigger_error ( «warning message form methodB» , E_WARNING );
>
public function methodC () <
echo( «methodC:n» );
throw new ErrorException ();
>
public function methodD () <
echo( «methodD:n» );
throw new ErrorException ( ‘warning message from methodD’ , 0 ,
E_WARNING );
>
public function run ( $i ) <
if ( $i === 0 ) <
$this -> methodA ();
> else if ( $i === 1 ) <
$this -> methodB ();
> else if ( $i === 2 ) <
$this -> methodC ();
> else <
$this -> methodD ();
>
>
public function test () <
for ( $i = 0 ; $i 4 ; ++ $i ) <
try <
$this -> run ( $i );
> catch ( ErrorException $e ) <
if ( $e -> getSeverity () === E_ERROR ) <
echo( «E_ERROR triggered.n» );
> else if ( $e -> getSeverity () === E_WARNING ) <
echo( «E_WARNING triggered.n» );
>
>
>
>
>
$myClass = new MyClass ();
$myClass -> test ();
?>
Please note that methodC() uses (constructor of) class ErrorException with default parameters.
I believe it is the original intention to make $severity having default value of 1, which is exactly equal to E_ERROR.
Using property $code or Exception::getCode() to compare with E_* values could not do the same thing (as in methodC()), as $code has a default value of 0, and class Exception has it too, users may use $code for some other purposes.
Источник
Предопределённые исключения
- Exception
- ErrorException
- Error
- ArgumentCountError
- ArithmeticError
- AssertionError
- DivisionByZeroError
- CompileError
- ParseError
- TypeError
Exception
Exception — это базовый класс для всех исключений в PHP 5 и базовый класс для всех пользовательских исключений в PHP 7.
До PHP 7 Exception не реализовывал интерфейс Throwable.
Exception implements Throwable {
/* Свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Методы */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public getMessage ( void ) : string
final public getPrevious ( void ) : Throwable
final public getCode ( void ) : mixed
final public getFile ( void ) : string
final public getLine ( void ) : int
final public getTrace ( void ) : array
final public getTraceAsString ( void ) : string
public __toString ( void ) : string
final private __clone ( void ) : void
}
Свойства:
- message — Текст исключения
- code — Код исключения
- file — Имя файла, в котором было вызвано исключение
- line — Номер строки, в которой было вызвано исключение
Методы:
- Exception::__construct — Создать исключение
- Exception::getMessage — Получает сообщение исключения
- Exception::getPrevious — Возвращает предыдущее исключение
- Exception::getCode — Получает код исключения
- Exception::getFile — Получает файл, в котором возникло исключение
- Exception::getLine — Получает строку, в которой возникло исключение
- Exception::getTrace — Получает трассировку стека
- Exception::getTraceAsString — Получает трассировку стека в виде строки
- Exception::__toString — Строковое представление исключения
- Exception::__clone — Клонировать исключение
ErrorException
Исключение в случае ошибки.
ErrorException extends Exception {
/* Свойства */
protected int $severity ;
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Методы */
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = E_ERROR [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
final public getSeverity ( void ) : int
/* Наследуемые методы */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}
Error
Error — базовый класс для всех внутренних ошибок PHP.
Error implements Throwable {
/* Свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Методы */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public getMessage ( void ) : string
final public getPrevious ( void ) : Throwable
final public getCode ( void ) : mixed
final public getFile ( void ) : string
final public getLine ( void ) : int
final public getTrace ( void ) : array
final public getTraceAsString ( void ) : string
public __toString ( void ) : string
final private __clone ( void ) : void
}
ArgumentCountError
ArgumentCountError выбрасывается когда в пользовательский метод или функцию передано недостаточное количество аргументов.
ArgumentCountError extends TypeError {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
ArithmeticError
ArithmeticError выбрасывается, когда возникает ошибка при выполнении математических операций. В PHP 7.0 такие ошибки возможно спровоцировать побитовым смещением на отрицательное значение, или вызовом функции intdiv(), приводящей значение, не входящее в допустимый интервал целых чисел (integer).
ArithmeticError implements Error {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
AssertionError
AssertionError выбрасывается, когда утверждение, сделанное с помощью assert(), терпит неудачу.
AssertionError implements Error {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
DivisionByZeroError
DivisionByZeroError выбрасывается при попытке поделить число на ноль.
DivisionByZeroError implements Error {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
CompileError
Исключение CompileError выбрасывается в некоторых ошибок компиляции, которые ранее выдавали фатальную ошибку.
CompileError extends Error {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
ParseError
ParseError выбрасывается, когда возникает ошибка при разборе PHP-кода, например, когда вызывается функция eval().
Начиная с PHP 7.3.0, класс ParseError наследуется от CompileError. Ранее этот класс расширял класс Error.
ParseError extends CompileError {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
TypeError
Есть три сценария, в которых будет выброшено исключение TypeError. Первый — тип аргумента, переданный функции, не соответствует типу, объявленному в функции для этого аргумента. Второй — тип возвращенного функцией значения не соответствует типу возврата, объявленному в функции. Третий — встроенной функции PHP было передано неверное количество аргументов (только для режима strict).
TypeError extends Error {
/* Наследуемые свойства */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
/* Наследуемые методы */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}
(PHP 7, PHP 
Введение
Error — базовый класс
для всех внутренних ошибок PHP.
Обзор классов
Свойства
- message
-
Сообщение об ошибке
- code
-
Код ошибки
- file
-
Имя файла, в котором произошла ошибка
- line
-
Номер строки, в которой произошла ошибка
- previous
-
Ранее выброшенное исключение
- string
-
Строковое представление трассировки стека
- trace
-
Трассировка стека в виде массива
Содержание
- Error::__construct — Создаёт объект класса Error
- Error::getMessage — Получает сообщение об ошибке
- Error::getPrevious — Возвращает предыдущий Throwable
- Error::getCode — Возвращает код ошибки
- Error::getFile — Получает файл, в котором произошла ошибка
- Error::getLine — Получает номер строки, в которой произошла ошибка
- Error::getTrace — Получает трассировку стека
- Error::getTraceAsString — Получает трассировку стека в виде строки
- Error::__toString — Строковое представление ошибки
- Error::__clone — Клонирует ошибку
whysteepy at gmail dot com ¶
5 years ago
Lists of Throwable and Exception tree as of 7.2.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
ArgumentCountError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/sDMsv
posted here http://php.net/manual/en/class.throwable.php
dams at php dot net ¶
1 year ago
Lists of Throwable and Exception tree as of 8.1.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
CompileError
ParseError
FiberError
TypeError
ArgumentCountError
UnhandledMatchError
ValueError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
JsonException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/f8Boe
Initially posted by whysteepy at gmail dot com for PHP 7.2.0, based on the gist
JustinasMalkas ¶
7 years ago
If after PHP upgrade you're getting error "PHP Fatal error: Cannot declare class error, because the name is already in use ...", you will have to rename your "error" class.
Since PHP 7 classname "Error" is predefined and used internally.
I have not yet been able to find a list of all the built-in Exception sub classes in PHP. I’d rather use built in ones when they make sense, before creating my own exception subclasses.
For example, I know InvalidArgumentException exists, but there appears to be nothing comparable to Java’s NullPointerException.
Does anyone have or can link to a list of the available Exception subclasses in PHP?
John Conde
216k98 gold badges453 silver badges495 bronze badges
asked May 31, 2012 at 17:19
6
PHP 5 has two built in exceptions
ExceptionErrorException
Libraries within PHP have their own built in exceptions
DOMExceptionDOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.IntlExceptionhis class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.PharExceptionThrown when working with the Phar classReflectionExceptionThrown when working with Reflection classes
SPL includes a few of its own built in exceptions:
BadFunctionCallExceptionA callback refers to an undefined function or if some arguments are missing.BadMethodCallExceptionA callback refers to an undefined method or if some arguments are missing.DomainExceptionA value does not adhere to a defined valid data domain.InvalidArgumentExceptionThe arguments passed were invalid.LengthExceptionThe parameter exceeds the allowed length (used for strings, arrays, file size, etc.).LogicExceptionGeneric error occurred in program logic.OutOfBoundsExceptionAn illegal index was requested.OutOfRangeExceptionAn illegal index was requested. This represents errors that should be detected at compile time.OverflowExceptionAdding an element to a full container.RangeExceptionIndicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow.RuntimeExceptionAn error which can only be found on runtime occurs.UnderflowExceptionPerforming an invalid operation on an empty container, such as removing an element.UnexpectedValueExceptionAn unexpected value was received (i.e. as the result of a returned value from a method call).
PHP 7 introduces new exceptions including catchable errors. New exceptions include:
Throwableis the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.Erroris the base class for all internal PHP errors.AssertionErroris thrown when an assertion made via assert() fails.ParseErroris thrown when an error occurs while parsing PHP code, such as when eval() is called.TypeErrorThere are three scenarios where a TypeError may be thrown. The first is where the argument type being passed to a function does not match its corresponding declared parameter type. The second is where a value being returned from a function does not match the declared function return type. The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only).ArithmeticErroris thrown when an error occurs while performing mathematical operations. In PHP 7.0, these errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an integer.DivisionByZeroErroris thrown when an attempt is made to divide a number by zero.ArgumentCountErroris thrown when too few arguments are passed to a user-defined function or method.
PHP 7.3 introduces JSON exceptions:
JsonExceptionis thrown whenjson_encode()andjson_decode()experience an error.
PHP 8 introduces one new exception:
ValueErroris thrown when you pass a value to a function, which has a valid type but can not be used for the operation.
PHP 8.3 will add new exceptions for Date/Time errors
Here’s a chart that demonstrates the new hierarchy introduced in PHP 7:
Throwable
├── Exception (implements Throwable)
| |── DOMException (extends Exception)
| ├── IntlException (extends Exception)
| ├── JsonException (extends Exception)
| |── PharException (extends Exception)
| |── ReflectionException (extends Exception)
| |── ValueError (extends Exception)
│ ├── LogicException (extends Exception)
│ │ ├── BadFunctionCallException (extends LogicException)
│ │ │ └── BadMethodCallException (extends BadFunctionCallException)
│ │ ├── DomainException (extends LogicException)
│ │ ├── InvalidArgumentException (extends LogicException)
│ │ ├── LengthException (extends LogicException)
│ │ └── OutOfRangeException (extends LogicException)
│ └── RuntimeException (extends Exception)
│ ├── OutOfBoundsException (extends RuntimeException)
│ ├── OverflowException (extends RuntimeException)
│ ├── RangeException (extends RuntimeException)
│ ├── UnderflowException (extends RuntimeException)
│ └── UnexpectedValueException (extends RuntimeException)
└── Error (implements Throwable)
├── AssertionError (extends Error)
├── ParseError (extends Error)
└── TypeError (extends Error)
└── ArgumentCountError (extends TypeError)
└── ArithmeticError (extends Error)
└── DivisionByZeroError extends ArithmeticError)
answered May 31, 2012 at 17:22
John CondeJohn Conde
216k98 gold badges453 silver badges495 bronze badges
6
I have not yet been able to find a list of all the built-in Exception sub classes in PHP. I’d rather use built in ones when they make sense, before creating my own exception subclasses.
For example, I know InvalidArgumentException exists, but there appears to be nothing comparable to Java’s NullPointerException.
Does anyone have or can link to a list of the available Exception subclasses in PHP?
John Conde
216k98 gold badges453 silver badges495 bronze badges
asked May 31, 2012 at 17:19
6
PHP 5 has two built in exceptions
ExceptionErrorException
Libraries within PHP have their own built in exceptions
DOMExceptionDOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.IntlExceptionhis class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.PharExceptionThrown when working with the Phar classReflectionExceptionThrown when working with Reflection classes
SPL includes a few of its own built in exceptions:
BadFunctionCallExceptionA callback refers to an undefined function or if some arguments are missing.BadMethodCallExceptionA callback refers to an undefined method or if some arguments are missing.DomainExceptionA value does not adhere to a defined valid data domain.InvalidArgumentExceptionThe arguments passed were invalid.LengthExceptionThe parameter exceeds the allowed length (used for strings, arrays, file size, etc.).LogicExceptionGeneric error occurred in program logic.OutOfBoundsExceptionAn illegal index was requested.OutOfRangeExceptionAn illegal index was requested. This represents errors that should be detected at compile time.OverflowExceptionAdding an element to a full container.RangeExceptionIndicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow.RuntimeExceptionAn error which can only be found on runtime occurs.UnderflowExceptionPerforming an invalid operation on an empty container, such as removing an element.UnexpectedValueExceptionAn unexpected value was received (i.e. as the result of a returned value from a method call).
PHP 7 introduces new exceptions including catchable errors. New exceptions include:
Throwableis the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.Erroris the base class for all internal PHP errors.AssertionErroris thrown when an assertion made via assert() fails.ParseErroris thrown when an error occurs while parsing PHP code, such as when eval() is called.TypeErrorThere are three scenarios where a TypeError may be thrown. The first is where the argument type being passed to a function does not match its corresponding declared parameter type. The second is where a value being returned from a function does not match the declared function return type. The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only).ArithmeticErroris thrown when an error occurs while performing mathematical operations. In PHP 7.0, these errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an integer.DivisionByZeroErroris thrown when an attempt is made to divide a number by zero.ArgumentCountErroris thrown when too few arguments are passed to a user-defined function or method.
PHP 7.3 introduces JSON exceptions:
JsonExceptionis thrown whenjson_encode()andjson_decode()experience an error.
PHP 8 introduces one new exception:
ValueErroris thrown when you pass a value to a function, which has a valid type but can not be used for the operation.
PHP 8.3 will add new exceptions for Date/Time errors
Here’s a chart that demonstrates the new hierarchy introduced in PHP 7:
Throwable
├── Exception (implements Throwable)
| |── DOMException (extends Exception)
| ├── IntlException (extends Exception)
| ├── JsonException (extends Exception)
| |── PharException (extends Exception)
| |── ReflectionException (extends Exception)
| |── ValueError (extends Exception)
│ ├── LogicException (extends Exception)
│ │ ├── BadFunctionCallException (extends LogicException)
│ │ │ └── BadMethodCallException (extends BadFunctionCallException)
│ │ ├── DomainException (extends LogicException)
│ │ ├── InvalidArgumentException (extends LogicException)
│ │ ├── LengthException (extends LogicException)
│ │ └── OutOfRangeException (extends LogicException)
│ └── RuntimeException (extends Exception)
│ ├── OutOfBoundsException (extends RuntimeException)
│ ├── OverflowException (extends RuntimeException)
│ ├── RangeException (extends RuntimeException)
│ ├── UnderflowException (extends RuntimeException)
│ └── UnexpectedValueException (extends RuntimeException)
└── Error (implements Throwable)
├── AssertionError (extends Error)
├── ParseError (extends Error)
└── TypeError (extends Error)
└── ArgumentCountError (extends TypeError)
└── ArithmeticError (extends Error)
└── DivisionByZeroError extends ArithmeticError)
answered May 31, 2012 at 17:22
John CondeJohn Conde
216k98 gold badges453 silver badges495 bronze badges
6
