How do you handle errors in PHP using try-catch blocks

Handling errors in PHP using try-catch blocks is a powerful method for managing exceptions and ensuring that your application can handle unexpected situations gracefully. The try-catch construct allows you to "try" a block of code, and if an exception occurs, it will "catch" that exception and let you handle it accordingly.

Here’s a basic example of how to use try-catch blocks in PHP:

<?php class CustomException extends Exception {} function testException($number) { if ($number > 1) { throw new CustomException("Number must be 1 or 0"); } return "Number is valid."; } try { echo testException(2); } catch (CustomException $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } catch (Exception $e) { echo 'Caught generic exception: ', $e->getMessage(), "\n"; } ?>

PHP try-catch error handling exception handling programming