How to throw exception in PHP?

Member

by brandy , in category: PHP General , a year ago

How to throw exception in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 9 months ago

@brandy 

To throw an exception in PHP, use the throw statement. Here's an example of how to throw an exception:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php

function divide($x, $y) {
  if ($y == 0) {
    throw new Exception("Division by zero");
  }
  return $x / $y;
}

try {
  $result = divide(10, 0);
} catch (Exception $e) {
  echo "Exception caught: " . $e->getMessage();
}

?>


In the example above, the divide function throws an exception if the second argument is 0. The try and catch blocks allow you to handle the exception and take appropriate action. The Exception class is the base class for all exceptions in PHP, and you can create custom exceptions by extending this class.


If you want to throw an exception of a specific type, you can create a custom exception class by extending the Exception class and then throw an instance of that class. Here's an example:

1
2
3
4
5
6
7
8
9
<?php

class MyCustomException extends Exception {
  // custom code goes here
}

throw new MyCustomException("Something went wrong");

?>