throw komandası

throw komandası PHP-də açıq şəkildə istisna yaratmaq üçün istifadə olunur. O, bir parametr qəbul edir - istisna obyekti, hansı ki, əsas Exception sinfindən miras alan sinifin nümunəsi olmalıdır. Bu funksiya çağırıldıqda, cari kodun icrası dərhal dayandırılır və PHP istisnanı emal etmək üçün uyğun catch blokunu axtarır.

Sintaksis

phpthrow new ExceptionClass(message, code, previous);

Nümunə

İstisna yaratmağın sadə nümunəsi:

php<?php
  $age = -5;
  if ($age < 0) {
    throw new Exception('Age cannot be negative');
  }
?>

Kodun icrasının nəticəsi:

phpFatal error: Uncaught Exception: Age cannot be negative

Nümunə

İstisnanın emalı ilə nümunə:

php<?php
  try {
    $res = 10 / 0;
    if (is_infinite($res)) {
      throw new Exception('Division by zero');
    }
  } catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
  }
?>

Kodun icrasının nəticəsi:

php'Error: Division by zero'

Nümunə

Xüsusi istisnanın istifadəsi:

php<?php
  class MyCustomException extends Exception {}
  
  try {
    throw new MyCustomException('Custom error message');
  } catch (MyCustomException $e) {
    echo 'Custom error caught: ' . $e->getMessage();
  }
?>

Kodun icrasının nəticəsi:

php'Custom error caught: Custom error message'

Həmçinin bax

  • try qurumunu,
    istisnaları emal etmək üçün kod blokunu təyin edən
  • catch qurumunu,
    istisnaları tutan və emal edən
  • Exception sinfini,
    bütün istisnalar üçün əsas sinif olan