362 of 410 menu

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

try { // 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 try { throw new Exception('Something went wrong'); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(); } ?>

Code execution result:

'Caught exception: Something went wrong'

Example

An example using the finally block:

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

Code execution result:

'Try block executed - Finally block executed'

Example

Handling different types of exceptions:

<?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:

'Invalid argument: Invalid argument'

See Also

byenru