PHP - Throwing Exceptions

Throwing Exceptions:

To throw an exception, you use the throw keyword followed by an instance of a class that extends the built-in Exception class or one of its subclasses. You can create your own custom exception classes for more specific error handling.

class CustomException extends Exception {
  // Your custom exception code
}
function divide($a, $b) {
  if ($b == 0) {
      throw new CustomException("Division by zero is not allowed.");
  }
  return $a / $b;
}
try {
  echo divide(10, 0);
} catch (CustomException $e) {
  echo "Caught exception: " . $e->getMessage();
}

Creating Custom Exception Classes:

Creating custom exception classes can make your error handling more meaningful and specific. Here's how you can define your own custom exception class:

class CustomException extends Exception {
  public function __construct($message = "", $code = 0, Throwable $previous = null) {
      parent::__construct("Custom: " . $message, $code, $previous);
  }
}
try {
  throw new CustomException("This is a custom exception.");
} catch (CustomException $e) {
  echo "Caught custom exception: " . $e->getMessage();
}

By using exceptions in your PHP code, you can improve the way you handle errors and exceptional situations, leading to more robust and maintainable applications.