try { // Some code that may throw an exception } catch (Exception $e) { // Output the error message echo $e->getMessage(); }
class CustomException extends Exception { public function __construct($message) { parent::__construct($message); } } try { // Some code that may throw a CustomException throw new CustomException("Something went wrong"); } catch (CustomException $e) { // Output the error message echo $e->getMessage(); }In this example, we create a custom exception class `CustomException` that extends the built-in `Exception` class. We can then throw this exception in our code, and catch it with a try-catch block. When we catch the exception, we can use `getMessage()` to display the error message that we passed to the constructor of our `CustomException` class. Package library: None (custom exception class)