PHP catch exceptions

PHP catch exceptions

Last Updated on Feb 14, 2023

Most of the time in your script you might face some exceptions, especially when you are handling unknown files or user inputs.

So today we are going to learn how to catch those exceptions.

In PHP the structure for catching exception is like this:

try {
  // your code here
} catch(Exception $e) {
  // what to do if there was an exception

We write the code in the try part. And in the catch part we tell php what to do if there was an exception

Catch accepts the type of exception you want to catch. In the above example we use Exception to accept all the exceptions and we tell PHP to store the exception (whatever it was) in the $e variable. (or you can name it whatever you want)

You can catch multiple exceptions by using multiple catches

For example

try {
   // your code here
} catch(Exception $e) {
   // what to do if there was an exception
} catch(ArithmeticError $e) {
   // what to do if there was an arithmetic error

Or you can use throwable to catch everything (all the exceptions and errors)

try {
  // your code here
} catch(Throwable $th) {
   // what to do if there was an exception or an error

Now let’s see an example

try {
   $x = 10;
} catch (Throwable $e) {
   echo 'x is not an object';

We can throw an exception ourselves by doing this

throw new Exception(message,code,previous)

Message: is the error message
Code: is the error code
Previous: is the previous throwable, you can use this is you want to chain the errors together

In the catch part we tell php to store the error or exception in the $e variable. The $e variable is an object and we can get very useful information from it, like the file or line that causes the error, error message and error code

Let’s see an example

try {
    $x = 10;
    if ($x > 7) {
        throw new Exception("x is too big", 70);
} catch (Throwable $th) {
// 5
// x is too big
// 70
// C:\xampp\htdocs\examples\index.php

Handling the errors and exceptions that might be thrown during your code is very important. And now you know how to do it. Isn’t it great?


Now you know about handling exceptions and errors in PHP.

I recommend you to open a PHP files and try to catch different types of errors and exceptions. try to throw exceptions and write your own message.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • try catch
  • catch exceptions
  • catch errors
  • throw exceptions
  • throwable

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts