The try Command

The try construct allows handling exceptions that may occur during code execution. Potentially dangerous code is placed in the try block, and the exception handler is placed in the catch block. The finally block can also be used, which executes in any case.

Syntax

phptry {
  // Code that may cause an exception
} catch (ExceptionType $e) {
  // Exception handling
} finally {
  // Code that will execute in any case
}

Example

A simple exception handling example:

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

Code execution result:

php'Caught exception: Something went wrong'

Example

An example using the finally block:

php<?php
try {
  echo 'Try block executed';
} finally {
  echo ' - Finally block executed';
}
?>

Code execution result:

php'Try block executed - Finally block executed'

Example

Handling different types of exceptions:

php<?php
try {
  // Code that may cause different exceptions
  throw new InvalidArgumentException('Invalid argument');
} catch (InvalidArgumentException $e) {
  echo 'Invalid argument: ', $e->getMessage();
} catch (Exception $e) {
  echo 'Generic exception: ', $e->getMessage();
}
?>

Code execution result:

php'Invalid argument: Invalid argument'

See Also