Klass Exception

Klassen Exception utgör basklassen för alla undantag i PHP. Den innehåller grundläggande metoder för att arbeta med undantag: att få felmeddelandet, felkoden, filen och radnumret där undantaget uppstod, samt anropsstacken. När man skapar ett undantag kan man skicka med ett meddelande, en felkod och ett tidigare undantag.

Syntax

phpnew Exception(string $message = "", int $code = 0, Throwable $previous = null);

Exempel

Låt oss skapa och hantera ett enkelt undantag:

php<?php
  try {
    throw new Exception('Något gick fel', 100);
  } catch (Exception $e) {
    echo 'Fel: ' . $e->getMessage();
  }
?>

Resultat av kodkörning:

php'Fel: Något gick fel'

Exempel

Låt oss använda huvudmetoderna i klassen Exception:

php<?php
  try {
    throw new Exception('Testundantag', 123);
  } catch (Exception $e) {
    echo 'Meddelande: ' . $e->getMessage() . "\n";
    echo 'Kod: ' . $e->getCode() . "\n";
    echo 'Fil: ' . $e->getFile() . "\n";
    echo 'Rad: ' . $e->getLine() . "\n";
  }
?>

Resultat av kodkörning (exempel):

php'Meddelande: Testundantag
Kod: 123
Fil: /sökväg/till/fil.php
Rad: 3'

Exempel

Låt oss få anropsstacken vid ett undantag:

php<?php
  function test() {
    throw new Exception('Stackspårningstest');
  }
  
  try {
    test();
  } catch (Exception $e) {
    print_r($e->getTrace());
  }
?>

Resultat av kodkörning (exempel):

php[
  [
    'file' => '/sökväg/till/fil.php',
    'line' => 5,
    'function' => 'test',
    'args' => []
  ]
]

Se även