в PHP для создания исключения. Я предоставлю вам несколько примеров использования throw.
-
Базовое исключение:
try { // Code that may throw an exception throw new Exception('This is a basic exception.'); } catch (Exception $e) { // Handle the exception echo 'Caught exception: ', $e->getMessage(), "\n"; } -
Пользовательское исключение:
class CustomException extends Exception {} try { // Code that may throw a custom exception throw new CustomException('This is a custom exception.'); } catch (CustomException $e) { // Handle the custom exception echo 'Caught custom exception: ', $e->getMessage(), "\n"; } -
Несколько исключений:
try { // Code that may throw multiple exceptions if (condition) { throw new Exception('Exception 1.'); } else { throw new CustomException('Exception 2.'); } } catch (Exception $e) { // Handle the first exception echo 'Caught exception: ', $e->getMessage(), "\n"; } catch (CustomException $e) { // Handle the second exception echo 'Caught custom exception: ', $e->getMessage(), "\n"; } -
Повторное создание исключений:
try { // Code that may throw an exception throw new Exception('This is an exception.'); } catch (Exception $e) { // Handle the exception or rethrow it if (condition) { throw $e; // Rethrow the exception } else { echo 'Caught exception: ', $e->getMessage(), "\n"; } } -
Использование Наконец:
try { // Code that may throw an exception throw new Exception('This is an exception.'); } catch (Exception $e) { // Handle the exception echo 'Caught exception: ', $e->getMessage(), "\n"; } finally { // Code that will always execute echo 'Finally block executed.', "\n"; }