Käsk throw

Käsku throw kasutatakse erandi selgesõnaliseks viskamiseks PHP-s. See võtab ühe parameetri - erandi objekti, mis peab olema klassi eksemplar, mis on päritud baasklassist Exception. Selle funktsiooni väljakutsumisel praegune koodi täitmine kohe peatub ja PHP proovib leida vastava catch ploki erandi töötlemiseks.

Süntaks

phpthrow new ExceptionClass(message, code, previous);

Näide

Lihtne näide erandi genereerimisest:

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

Koodi täitmise tulemus:

phpFatal error: Uncaught Exception: Age cannot be negative

Näide

Näide erandi töötlemisega:

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

Koodi täitmise tulemus:

php'Error: Division by zero'

Näide

Kohandatud erandi kasutamine:

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

Koodi täitmise tulemus:

php'Custom error caught: Custom error message'

Vaata ka

  • konstruktsiooni try,
    mis määratleb koodiploki erandite töötlemiseks
  • konstruktsiooni catch,
    mis püüab ja töötleb erandeid
  • klassi Exception,
    mis on baasklass kõikidele eranditele