How to throw exception in PHP?

Member

by brandy , in category: PHP General , 2 years ago

How to throw exception in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , 2 years 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");

?>


by haylee.mertz , a year ago

@brandy 

To throw an exception in PHP, you can use the throw statement. Here is an example:

 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 above example, the divide function throws an exception if the second argument is 0. The try block is used to execute the code that may throw an exception. If an exception is thrown, it is caught by the catch block, where you can handle and process the exception.


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 is 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");

?>


In the above example, the MyCustomException class is created by extending the base Exception class. You can add custom code and properties to the MyCustomException class. Then, you can create an instance of MyCustomException and throw it as an exception.