Funktsioon catch

Funktsioon catch on osa try-catch plokist ja kasutatakse erindite püüdmiseks, mida võib visata plokis try. Erindi tekkimisel läheb koodi täitmine vastavasse plokki catch, kus saab vea töödelda.

Süntaks

phptry {
  // Kood, mis võib visata erindi
} catch (ExceptionType $e) {
  // Erindi töötlemine
}

Näide

Lihtsaim näide erindi töötlemisest:

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

Koodi täitmise tulemus:

php'Caught exception: Something went wrong'

Näide

Erinevat tüüpi erindite töötlemine:

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();
  }
?>

Võimalikud koodi täitmise tulemused:

php'Invalid argument: Invalid argument'
või
'Runtime error: Runtime error'

Vaata ka

  • konstruktsiooni try,
    mis määratleb koodiploki erindite töötlemiseks
  • konstruktsiooni throw,
    mis viskab erindi
  • klassi Exception,
    mis on baasklass kõikidele erinditele