Funkcija catch

Funkcija catch yra try-catch bloko dalis ir naudojama išimtims pagauti, kurios gali būti išmestos try bloke. Išmetus išimtį, kodas pereina į atitinkamą catch bloką, kur galima apdoroti klaidą.

Sintaksė

phptry {
  // Kodas, kuris gali išmesti išimtį
} catch (ExceptionType $e) {
  // Išimties apdorojimas
}

Pavyzdys

Paprasčiausias išimties apdorojimo pavyzdys:

php<?php
  try {
    throw new Exception('Something went wrong');
  } catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage();
  }
?>

Kodo vykdymo rezultatas:

php'Caught exception: Something went wrong'

Pavyzdys

Skirtingų tipų išimčių apdorojimas:

php<?php
  try {
    if (rand(0, 1)) {
      throw new InvalidArgumentException('Invalid argument');
    } else {
      throw new RuntimeException('Runtime error');
    }
  } catch (InvalidArgumentException $e) {
    echo 'Invalid argument: ' . $e->getMessage();
  } catch (RuntimeException $e) {
    echo 'Runtime error: ' . $e->getMessage();
  } catch (Exception $e) {
    echo 'Generic exception: ' . $e->getMessage();
  }
?>

Galimi kodo vykdymo rezultatai:

php'Invalid argument: Invalid argument'
arba
'Runtime error: Runtime error'

Taip pat žiūrėkite

  • konstrukciją try,
    kuri apibrėžia kodo bloką išimtims apdoroti
  • konstrukciją throw,
    kuri išmeta išimtį
  • klasę Exception,
    kuri yra bazinis klasė visoms išimtims