363 of 410 menu

The catch Function

The catch function is part of the try-catch block and serves to intercept exceptions that may be thrown in the try block. When an exception occurs, code execution moves to the corresponding catch block, where the error can be handled.

Syntax

try { // Code that may throw an exception } catch (ExceptionType $e) { // Exception handling }

Example

A simple exception handling example:

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

Code execution result:

'Caught exception: Something went wrong'

Example

Handling different types of exceptions:

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

Possible code execution results:

'Invalid argument: Invalid argument' or 'Runtime error: Runtime error'

See Also

  • the try construct,
    which defines a code block for exception handling
  • the throw construct,
    which throws an exception
  • the Exception class,
    which is the base class for all exceptions
byenru