Funksie catch
Die funksie catch is deel van die try-catch blok en dien om uitsonderings te vang wat in die try-blok gegooi mag word. Wanneer 'n uitsondering voorkom, gaan die uitvoering van kode oor na die ooreenstemmende catch-blok, waar die fout verwerk kan word.
Sintaksis
try {
// Kode wat 'n uitsondering kan gooi
} catch (ExceptionType $e) {
// Verwerking van uitsondering
}
Voorbeeld
'n Eenvoudige voorbeeld van uitsonderingsverwerking:
<?php
try {
throw new Exception('Iets het verkeerd geloop');
} catch (Exception $e) {
echo 'Uitsondering gevang: ' . $e->getMessage();
}
?>
Resultaat van kode-uitvoering:
'Uitsondering gevang: Iets het verkeerd geloop'
Voorbeeld
Verwerking van verskillende tipes uitsonderings:
<?php
try {
if (rand(0, 1)) {
throw new InvalidArgumentException('Ongeldige argument');
} else {
throw new RuntimeException('Runtime fout');
}
} catch (InvalidArgumentException $e) {
echo 'Ongeldige argument: ' . $e->getMessage();
} catch (RuntimeException $e) {
echo 'Runtime fout: ' . $e->getMessage();
} catch (Exception $e) {
echo 'Generiese uitsondering: ' . $e->getMessage();
}
?>
Moontlike resultate van kode-uitvoering:
'Ongeldige argument: Ongeldige argument'
of
'Runtime fout: Runtime fout'