Исключения

Модель исключений (exceptions) в PHP 5 проще, чем в других языках программирования Исключение можно сгенерировать (как говорят, "выбросить") при помощи оператора throw, и можно перехватить (или, как говорят, "поймать") оператором catch. Код выбрасывающий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий блок catch. Так же можно использовать несколько блоков catch, перехватывающих различные классы исключений. Нормальное выполнение (когда не генерируется исключений в блоках try или когда класс выброшенного исключения не совпадает с классами, объявленными в соответствующих блоках catch) будет продолжено за последним блоком catch. Исключения так же могут быть сгенерированны (или перегерерированы - т.е. выброшены снова) оператором throw внутри блока catch.

При генерации исключения, код следующий ниже оператора throw исполнен не будет, а PHP предпримет попытку найти первый блок catch, перехватывающий исключение данного класса. Если исключение не будет перехвачено, PHP выдаст сообщение об ошибке: "Uncaught Exception ..." (Неперехваченное исключение), если конечно не был определен обработчик ошибок при помощи функции set_exception_handler().

Пример #1 Выброс исключений

<?php
function inverse($x) {
    if (!
$x) {
        throw new 
Exception('Деление на ноль.');
    }
    else return 
1/$x;
}

try {
    echo 
inverse(5) . "\n";
    echo 
inverse(0) . "\n";
} catch (
Exception $e) {
    echo 
'Выброшено исключение: ',  $e->getMessage(), "\n";
}

// Продолжение выполнения
echo 'Hello World';
?>

Результат выполнения данного примера:

0.2
Выброшено исключение: Деление на ноль.
Hello World

Наследование исключений

Определенный пользователем класс исключения должен быть определен, как класс расширяющий (наследующий) встроенный класс Exception. Ниже приведены методы и свойства класса Exception, доступные дочерним классам.

Пример #2 Встроеный класс Exception

<?php
class Exception
{
    protected 
$message 'Unknown exception';   // сообшение
    
protected $code 0;                        // Код исключения,
    
определяемый пользователем
    
protected $file;                            // файл в котором было
    
выброшено исключение
    
protected $line;                            // строка в которой было
    
выброшено исключение

    
function __construct($message null$code 0);

    final function 
getMessage();                // Возвращает сообшение
    
исключения 
    
final function getCode();                   // Код исключения
    
final function getFile();                   // Файл, где выброшено
    
исключение
    
final function getLine();                   // Строка, выбросившая исключени
    
final function getTrace();                  // Массив backtrace()
    
final function getTraceAsString();          // Обратная трассировка как
    
строка

    
/* Overrideable - т.е. то, что можно переопределить */
    
function __toString();                       // должен вернуть
    
форматированную строкудля отображения
}
?>

Если класс, наследуемый от Exception переопределяет конструктор, необходимо вызвать в конструкторе parent::__construct(), чтобы быть уверенным, что все дынные будут доступны. Метод __toString() может быть переопределен, что бы обеспечить нужный вывод, когда объект преобразуется в строку.

Пример #3 Наследование класса Exception

<?php
/**
 * Определим свой класс исключения
 */
class MyException extends Exception
{
    
// Переопределим исключение так, что параметр message станет обязательным
    
public function __construct($message$code 0) {
        
// какой-то код 
    
        
parent::__construct($message$code);
    }

    
// Переопределим строковое представление объекта.
    
public function __toString() {
        return 
__CLASS__ ": [{$this->code}]: {$this->message}\n";
    }

    public function 
customFunction() {
        echo 
"Мы можем определять новые методы в наследуемом классе\n";
    }
}


/**
 * Создадим класс для тестирования исключения
 */
class TestException
{
    public 
$var;

    const 
THROW_NONE    0;
    const 
THROW_CUSTOM  1;
    const 
THROW_DEFAULT 2;

    function 
__construct($avalue self::THROW_NONE) {

        switch (
$avalue) {
            case 
self::THROW_CUSTOM:
                
// Бросаем собственное исключение
                
throw new MyException('1 - неправильный параметр'5);
                break;

            case 
self::THROW_DEFAULT:
                
// Бросаем встроеное исключение
                
throw new Exception('2 - недопустимый параметр'6);
                break;

            default: 
                
// Никаких исключений, объект будет создан.
                
$this->var $avalue;
                break;
        }
    }
}


// Example 1
try {
    
$o = new TestException(TestException::THROW_CUSTOM);
} catch (
MyException $e) {      // Will be caught
    
echo "Поймано собственное, переопределенное исключение\n"$e;
    
$e->customFunction();
} catch (
Exception $e) {        // Будет пропущено.
    
echo "Поймано встроенное исключение\n"$e;
}

// Отсюда будет продолжено выполнение программы
var_dump($o);
echo 
"\n\n";


// Example 2
try {
    
$o = new TestException(TestException::THROW_DEFAULT);
} catch (
MyException $e) {      // Тип исключения не совпадет
    
echo "Поймано переопределенное исключение\n"$e;
    
$e->customFunction();
} catch (
Exception $e) {        // Будет перехвачено
    
echo "Перехвачено встроенное исключение\n"$e;
}

// Отсюда будет продолжено выполнение программы
var_dump($o);
echo 
"\n\n";


// Example 3
try {
    
$o = new TestException(TestException::THROW_CUSTOM);
} catch (
Exception $e) {        // Будет перехвачено.
    
echo "Поймано встроенное исключение\n"$e;
}

// Продолжение исполнения программы
var_dump($o);
echo 
"\n\n";


// Example 4
try {
    
$o = new TestException();
} catch (
Exception $e) {        // Будет пропущено, т.к. исключение не выкидывается
    
echo "Поймано встроенное исключение\n"$e;
}

// Продолжение выполнения программы
var_dump($o);
echo 
"\n\n";
?>

Коментарии

‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).
2008-10-21 15:13:17
http://php5.kiev.ua/manual/ru/language.exceptions.html
If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
   
/* Protected methods inherited from Exception class */
   
public function getMessage();                 // Exception message 
   
public function getCode();                    // User-defined Exception code
   
public function getFile();                    // Source filename
   
public function getLine();                    // Source line
   
public function getTrace();                   // An array of the backtrace()
   
public function getTraceAsString();           // Formated string of trace
   
    /* Overrideable methods inherited from Exception class */
   
public function __toString();                 // formated string for display
   
public function __construct($message null$code 0);
}

abstract class 
CustomException extends Exception implements IException
{
    protected 
$message 'Unknown exception';     // Exception message
   
private   $string;                            // Unknown
   
protected $code    0;                       // User-defined exception code
   
protected $file;                              // Source filename of exception
   
protected $line;                              // Source line of exception
   
private   $trace;                             // Unknown

   
public function __construct($message null$code 0)
    {
        if (!
$message) {
            throw new 
$this('Unknown 'get_class($this));
        }
       
parent::__construct($message$code);
    }
   
    public function 
__toString()
    {
        return 
get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                               
"{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new 
TestException();
    }
    catch (
TestException $e) {
        echo 
"Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (
Exception $e) {
        echo 
"Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo 
'<pre>' exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
2009-05-27 15:19:13
http://php5.kiev.ua/manual/ru/language.exceptions.html
Автор:
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start
();
try {
   
/*contains all page logic 
    and throws error if needed*/
   
...
} catch (
Exception $e) {
 
ob_end_clean();
 
displayErrorPage($e->getMessage());
}
?>
2011-05-05 04:18:51
http://php5.kiev.ua/manual/ru/language.exceptions.html
Автор:
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name 
"Name";

//check if the name contains only letters, and does not contain the word name

try
   {
   try
     {
      if (
preg_match('/[^a-z]/i'$name)) 
       {
           throw new 
Exception("$name contains character other than a-z A-Z");
       }   
       if(
strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new 
Exception("$name contains the word name");
       }
       echo 
"The Name is valid";
     }
   catch(
Exception $e)
     {
     throw new 
Exception("insert name again",0,$e);
     }
   }
 
catch (
Exception $e)
   {
   if (
$e->getPrevious())
   {
    echo 
"The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
   }
   echo 
"The Exception is: ".$e->getMessage()."<br/>";
   }

 
?>
2011-11-28 23:36:00
http://php5.kiev.ua/manual/ru/language.exceptions.html
Автор:
The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
        try {
                throw new 
\Exception("Hello");
        } catch(
\Exception $e) {
                echo 
$e->getMessage()." catch in\n";
                throw 
$e;
        } finally {
                echo 
$e->getMessage()." finally \n";
                throw new 
\Exception("Bye");
        }
} catch (
\Exception $e) {
        echo 
$e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally 
Bye catch out
2013-06-24 21:13:34
http://php5.kiev.ua/manual/ru/language.exceptions.html
When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block. 

<?php
try {
    echo 
"try block<br />";
    throw new 
Exception("test");
} catch (
Exception $ex) {
    echo 
"catch block<br />";
} finally {
    echo 
"finally block<br />";
}

// try block
// catch block
// finally block
?>

<?php
try {
    echo 
"try block<br />";
    throw new 
Exception("test");
} catch (
Exception $ex) {
    echo 
"catch block<br />";
    exit(
1);
} finally {
    echo 
"finally block<br />";
}

// try block
// catch block
?>
2014-06-18 15:34:04
http://php5.kiev.ua/manual/ru/language.exceptions.html
Автор:
Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.
2014-12-04 15:45:20
http://php5.kiev.ua/manual/ru/language.exceptions.html
Автор:
#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.
2015-04-04 05:47:31
http://php5.kiev.ua/manual/ru/language.exceptions.html
In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

<?php 
    set_error_handler
(function($errno$errstr$errfile$errline){
            if(
$errno === E_WARNING){
               
// make it more serious than a warning so it can be caught
               
trigger_error($errstrE_ERROR);
                return 
true;
            } else {
               
// fallback to default php error handler
               
return false;
            }
    });

    try {
           
// code that might result in a E_WARNING
   
} catch(Exception $e){
           
// code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
   
} finally {
           
restore_error_handler();
    }
?>
2017-06-15 13:12:33
http://php5.kiev.ua/manual/ru/language.exceptions.html
Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

<?php

try {
    throw new 
Error"foobar" );
   
// or:
    // throw new Exception( "foobar" );
}
catch (
Throwable $e) {
   
var_export$e );
}

?>
2017-09-22 16:13:37
http://php5.kiev.ua/manual/ru/language.exceptions.html
<?php

/**
 * You can catch exceptions thrown in a deep level function
 */

function employee()
{
    throw new 
\Exception("I am just an employee !");
}

function 
manager()
{
   
employee();
}

function 
boss()
{
    try {
       
manager();
    } catch (
\Exception $e) {
        echo 
$e->getMessage();
    }
}

boss(); // output: "I am just an employee !"
2018-02-24 11:49:41
http://php5.kiev.ua/manual/ru/language.exceptions.html
Note some undocumented details about exceptions thrown from 'finally' blocks. 

When exception is thrown from 'finally' block, it overrides the original not-caught (or re-thrown) exception. So the behavior is similar to 'return': value returned from 'finally' overrides the one returned earlier. And the original exception is automatically appended to the exceptions chain, i.e. becomes 'previous' for the new one. Example:
<?php
try {
    try {
        throw new 
Exception('thrown from try');
    } finally {
        throw new 
Exception('thrown from finally');
    }
} catch(
Exception $e) {
    echo 
$e->getMessage();
    echo 
PHP_EOL;
    echo 
$e->getPrevious()->getMessage();


// will output:
// thrown from finally
// thrown from try
?>

Example with re-throwing:
<?php
try {
    try {
        throw new 
Exception('thrown from try');
    } catch (
Exception $e) {
        throw new 
Exception('thrown from catch');
    } finally {
        throw new 
Exception('thrown from finally');
    }
} catch(
Exception $e) {
    echo 
$e->getMessage();
    echo 
PHP_EOL;
    echo 
$e->getPrevious()->getMessage();


// will output:
// thrown from finally
// thrown from catch
?>

The same happens even if explicitly pass null as previous exception:
<?php
try {
    try {
        throw new 
Exception('thrown from try');
    } finally {
        throw new 
Exception('thrown from finally'nullnull);
    }
} catch(
Exception $e) {
    echo 
$e->getMessage();
    echo 
PHP_EOL;
    echo 
$e->getPrevious()->getMessage();


// will output:
// thrown from finally
// thrown from try
?>

Also it is possible to pass previous exception explicitly, the 'original' one will be still appended to the chain, e.g.:
<?php
try {
    try {
        throw new 
Exception('thrown from try');
    } finally {
        throw new 
Exception(
           
'thrown from finally',
           
null
            new 
Exception('Explicitly set previous!')
        );
    }
} catch(
Exception $e) {
    echo 
$e->getMessage();
    echo 
PHP_EOL;
    echo 
$e->getPrevious()->getMessage();
    echo 
PHP_EOL;
    echo 
$e->getPrevious()->getPrevious()->getMessage();


// will output:
// thrown from finally
// Explicitly set previous!
// thrown from try
?>

This seems to be true for versions 5.6-8.2.
2022-12-23 02:24:20
http://php5.kiev.ua/manual/ru/language.exceptions.html
<?php

try {
 
$str 'hi';
  throw new 
Exception();
} catch (
Exception) {
 
var_dump($str);
} finally {
 
var_dump($str);
}

?>

Output:
string(2) "hi"
string(2) "hi"
2023-01-16 18:03:55
http://php5.kiev.ua/manual/ru/language.exceptions.html
Easy to understand `finally`.
<?php
try {
    try {
        echo 
"before\n";
       
0;
        echo 
"after\n";
    } finally {
        echo 
"finally\n";
    }
} catch (
\Throwable) {
    echo 
"exception\n";
}
?>
# Print:
before
finally
exception
2023-09-08 06:11:25
http://php5.kiev.ua/manual/ru/language.exceptions.html
Автор:
As noted elsewhere, throwing an exception from the `finally` block will replace a previously thrown exception. But the original exception is magically available from the new exception's `getPrevious()`.

<?php
try {
    try {
        throw new 
RuntimeException('Exception A');
    } finally {
        throw new 
RuntimeException('Exception B');
    }
}
catch (
Throwable $exception) {
    echo 
$exception->getMessage(), "\n";
   
// 'previous' is magically available!
   
echo $exception->getPrevious()->getMessage(), "\n";
}
?>

Will print:

Exception B
Exception A
2024-01-19 10:24:31
http://php5.kiev.ua/manual/ru/language.exceptions.html

    Поддержать сайт на родительском проекте КГБ