Php throw existing exception

Исключения

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

Генерируемый объект должен принадлежать классу Exception или наследоваться от Exception. Попытка сгенерировать исключение другого класса приведет к неисправимой ошибке.

catch

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

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

finally

В PHP 5.5 и более поздних версиях также можно использовать блок finally после или вместо блока catch. Код в блоке finally всегда будет выполняться после кода в блоках try и catch, вне зависимости было ли брошено исключение или нет, перед тем как продолжится нормальное выполнение кода. whether an exception has been thrown, and before normal execution resumes.

Читайте также:  Css pause play button

Примечания

Замечание:

Внутренние функции PHP в основном используют сообщения об ошибках, и только новые объектно-ориентированные расширения используют исключения. Однако, ошибки можно легко преобразовать в исключения с помощью класса ErrorException.

Примеры

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

function inverse ( $x ) if (! $x ) throw new Exception ( ‘Деление на ноль.’ );
>
return 1 / $x ;
>

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

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

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

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

Пример #4 Вложенные исключения

function inverse ( $x ) if (! $x ) throw new Exception ( ‘Деление на ноль.’ );
>
return 1 / $x ;
>

try echo inverse ( 5 ) . «\n» ;
> catch ( Exception $e ) echo ‘Поймано исключение: ‘ , $e -> getMessage (), «\n» ;
> finally echo «Первое finally.\n» ;
>

try echo inverse ( 0 ) . «\n» ;
> catch ( Exception $e ) echo ‘Поймано исключение: ‘ , $e -> getMessage (), «\n» ;
> finally echo «Второе finally.\n» ;
>

// Продолжение нормального выполнения
echo «Hello World\n» ;
?>

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

0.2 Первое finally. Поймано исключение: Деление на ноль. Второе finally. Hello World

Пример #5 Вложенные исключения

class MyException extends Exception

class Test public function testing () try try throw new MyException ( ‘foo!’ );
> catch ( MyException $e ) // повторный выброс исключения
throw $e ;
>
> catch ( Exception $e ) var_dump ( $e -> getMessage ());
>
>
>

$foo = new Test ;
$foo -> testing ();

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

Источник

PHP throw Exception

Summary: in this tutorial, you will learn about the Exception class in detail and how to throw a new exception in PHP.

Introduction to the Exception class

When encountering a situation from which you cannot recover, you can throw an exception.

An exception is an instance of the Exception class. Like other PHP objects, you use the new keyword to create an instance of the Exception class.

An Exception object has two main properties: a message and a numeric code. The message describes the exception. The numeric code is optional, which specifies the context for a specific exception.

When you create a new exception, you provide the mesage the optional numeric code. For example:

 $exception = new Exception('Invalid username or password', 100);Code language: HTML, XML (xml)

The Exception object has the getMessage() and getCode() that returns the message and numeric code:

 $exception = new Exception('Invalid username or password', 100); $message = $exception->getMessage(); $code = $exception->getCode();Code language: HTML, XML (xml)

The throw statement

In practice, you rarely assign an exception to a variable. Instead, you raise (or throw) the Exception object using the throw statement:

 throw new Exception('Invalid username or password', 100);Code language: HTML, XML (xml)

The throw statement accepts an instance of the Exception class or the subclass of the Exception class. In fact, it accepts any object that implements the Throwable interface. Note that the Exception class also implements the Throwable interface.

When PHP encounters a throw statement, it immediately halts the code execution. Therefore, the code after the throw statement won’t execute.

Throwing an exception example

The following example defines a function called divide() that uses the the throw statement:

function divide($x, $y) < if (!is_numeric($x) || !is_numeric($y)) < throw new InvalidArgumentException('Both arguments must be numbers or numeric strings'); > if ($y == 0) < throw new Exception('Division by zero, y cannot be zero'); > return $x / $y; >Code language: PHP (php)

How the define() function works.

  • First, throw the InvalidArgumentException exception if $x and $y are not numbers or numeric strings.
  • Second, throw the division by zero exception if $y is zero.
  • Third, return the division of $x and $y .

PHP built-in exception classes

The standard PHP library (SPL) provides many subclasses of the Exception class. For example, you can use the InvalidArgumentException when an argument of a function or method is not valid.

The following shows the exception classes in PHP 8.0:

Exception ClosedGeneratorException DOMException ErrorException IntlException JsonException LogicException BadFunctionCallException BadMethodCallException DomainException InvalidArgumentException LengthException OutOfRangeException PharException ReflectionException RuntimeException OutOfBoundsException OverflowException PDOException RangeException UnderflowException UnexpectedValueException SodiumExceptionCode language: plaintext (plaintext)

Summary

  • An exception is an instance of the Exception class that implements the Throwable interface.
  • Use the throw statement to raise an exception. The throw statement accepts an exception object that implements the Throwable interface.

Источник

Оцените статью