When should i use try catch php?

It seems to me that this topic is very strange and confused. Could someone lights me up?

Definitely. I'm not a PHP user, but I might have a little insight after having worked with try/catch in ActionScript, Java, and JavaScript. Bear in mind though, that different languages and platforms encourage different uses for try/catch. That said...

The only times I'd recommend using try/catch is if you're using a native language function that

  1. Can throw an error/exception
  2. Does not give you any tools to detect whether you're about to do something stupid that would cause that error/exception. eg: In ActionScript, closing a loader that is not open will result in an error but the loader doesn't have an isOpen property to check so you're forced to wrap it in try/catch to silence an otherwise totally meaningless error.
  3. The error/exception really is meaningless.

Let's take the examples you list and see how they square with that list.

I read someone saying that we should use try-catch blocks only to prevent fatal errors.

In the case of AS's loader.close() function, this is good advice. That's a fatal error, and all from an otherwise trivial misstep. On the other hand, virtually ALL errors in AS will bring your application to a halt. Would you then wrap them all in try/catch? Absolutely not! A "fatal error" is fatal for a reason. It means something terribly wrong has happened and for the application to continue on in a potentially "undefined" state is foolhardy. It's better to know an error happened and then fix it rather than just let it go.

I read someone else saying that we should use it only on unexpected errors

That's even worse. Those are presicely the errors you DON'T want to silence, because silencing them means that you're never going to find them. Maybe you're not swallowing them, though... maybe you're logging them. But why would you try/catch/log/continue as though nothing happened, allowing the program to run in a potentially dangerous and unexpected condition? Just let the error kick you in the teeth and then fix it. There's little more frustrating than trying to debug something that's wrong in a program that someone else wrote because they wrapped everything in a try/catch block and then neglected to log.

Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).

There's potential merit to this if you're the one doing the throwing, and you're trying to alert yourself to an exceptional situation in your program... but why try/catch your own thrown error? Let it kick you in the teeth, then fix it so that you don't need to throw the error anymore.

Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this i find a nice SO question about performance).

Maybe so. I can't answer this one though.

So... this might be a bit of a religious question, and I'm certain people will disagree with me, but from my particular vantage point those are the lessons I've learned over the years about try/catch.

When PHP version 5 was released, it incorporated a built-in model to catch errors and exceptions. Handling errors in PHP with try catch blocks is almost the same as handling errors in other programming languages.

When a PHP exception is thrown, the PHP runtime looks for a catch statement that can handle that type of exception. It will continue checking the calling methods up the stack trace until a catch statement is found. If one is not found, the exception is handed to the global exception handler that we will also cover in this article.

Simple PHP try catch example

Here is an example of a basic PHP try catch statement.

try {
    // run your code here
}
catch (exception $e) {
    //code to handle the exception
}
finally {
    //optional code that always runs
}

PHP error handling keywords

The following keywords are used for PHP exception handling.

  • Try: The try block contains the code that may potentially throw an exception. All of the code within the try block is executed until an exception is potentially thrown.
  • Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception.
  • Catch: This block of code will be called only if an exception occurs within the try code block. The code within your catch statement must handle the exception that was thrown.
  • Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes. This is useful for scenarios like closing a database connection regardless if an exception occurred or not.

PHP try catch with multiple exception types

PHP supports using multiple catch blocks within try catch. This allows us to customize our code based on the type of exception that was thrown. This is useful for customizing how you display an error message to a user, or if you should potentially retry something that failed the first time.

try {
    // run your code here
}
catch (Exception $e) {
    echo $e->getMessage();
}
catch (InvalidArgumentException $e) {
    echo $e->getMessage();
}

When to use try catch-finally

In PHP version 5.5, the finally block was added. Sometimes in your PHP error handling code, you will also want to use a finally section. Finally is useful for more than just exception handling, it is used to perform cleanup code such as closing a file, closing a database connection, etc.

The finally block always executes when the try catch block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Example for try catch-finally:

try {
    print "this is our try block n";
    throw new Exception();
} catch (Exception $e) {
    print "something went wrong, caught yah! n";
} finally {
    print "this part is always executed n";
}

Below is the diagram showing how the program works.

When should i use try catch php?

Creating custom PHP exception types

PHP also allows creating custom exception types.This can be useful for creating custom exceptions in your application that you can have special exception handling around.

To create a custom exception handler, we must create a special class with functions that can be called when an exception occurs. The class must be an extension of the exception class.

class DivideByZeroException extends Exception {};

The custom exception class inherits the properties from PHP’s Exception class and you can add custom functions to it. You may not want to display all the details of an exception to the user or you can display a user-friendly message and log the error message internally for monitoring.

The sample below uses a custom PHP exception with multiple catch statements.

class DivideByZeroException extends Exception {};
class DivideByNegativeException extends Exception {};

function process_divide($denominator)
{
    try
    {
        if ($denominator == 0)
        {
            throw new DivideByZeroException();
        }
        else if ($denominator < 0)
        {
            throw new DivideByNegativeException();
        }
        else
        {
            echo 100 / $denominator;
        }
    }
    catch (DivideByZeroException $ex)
    {
        echo "Divide by zero exception!";
    }
    catch (DivideByNegativeException $ex)
    {
        echo "Divide by negative number exception!";
    }
    catch (Exception $x)
    {
        echo "UNKNOWN EXCEPTION!";
    }
}

The code above throws an exception and catches it with a custom exception class. The DivideByZeroException() and DivideByNegativeException() classes are created as extensions of the existing Exception class; this way, it inherits all methods and properties from the Exception class. The “try” block is executed and an exception is thrown if the denominator is zero or negative number. The “catch” block catches the exception and displays the error message.

The flowchart below summarizes how our sample code above works for custom types of exceptions.

When should i use try catch php?

Global PHP exception handling

In a perfect world, your code will do proper exception handling. As a best practice, you should also configure a global PHP exception handler. It will be called in case an unhandled exception occurs that was not called in a proper PHP try catch block.

To configure a global PHP exception handler, we will use the set_exception_handler() function to set a user-defined function to handle all uncaught exceptions:

function our_global_exception_handler($exception) {
    //this code should log the exception to disk and an error tracking system
    echo "Exception:" . $exception->getMessage();
}

set_exception_handler(‘our_global_exception_handler’);

How to properly log exceptions in your PHP try catch blocks

Logging is usually the eyes and ears for most developers when it comes to troubleshooting application problems. Logging exceptions so you can find them after they happen is a really important part of PHP error handling best practices.

Try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.

Error logs are crucial during development because it allows developers to see warnings, errors, notices, etc. that were logged while the application is running. That you can handle them appropriately through the PHP exception handling techniques try catch we just learned.

Depending on the PHP framework you are using, whether Laravel, Codeigniter, Symfony, or others, they may provide built-in logging frameworks. You can also use Monolog, which is a standard PHP logging library. Regardless of the logging framework you are using, you want to always log important exceptions being thrown in your code.

Here is a sample of a try/catch that logs errors with Monolog:

require_once(DIR.'/vendor/autoload.php');
use MonologLogger;
use MonologHandlerStreamHandler;

$logger = new Logger('channel-name');
$logger->pushHandler(new StreamHandler(DIR.'/app.log', Logger::DEBUG));

try {
    // Code does some stuff
    // debug logging statement
    $logger->info('This is a log! ^_^ ');
}
catch (Exception $ex) {
    $logger->error('Oh no an exception happened! ');
}

How to use try catch with MySQL

The PHP libraries for MySQL, PDO, and mysqli, have different modes for error handling. If you do not have exceptions enables for those libraries, you can’t use try catch blocks. This makes error handling different and perhaps more complicated.

PDO

In PDO, you must enable ERRMODE_EXCEPTION when creating the connection.

// connect to MySQL
$conn = new PDO('mysql:host=localhost;dbname=stackifydb;charset=utf8mb4', 'username', 'password');
//PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Learn more about PDO attributes from the PHP docs.

MySQL

For mysqli, you must do something similar:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Learn more from the MySQL docs.

How to view all PHP exceptions in one place

Proper exception handling in PHP is very important. As part of that, you don’t want to simply log your exceptions to a log file and never know they occurred.

The solution is to use an error tracking solution like Stackify’s Retrace. All errors are recorded together with some important details about that error, including the time it occurred, the method that caused it, and the exception type.

Retrace provides many important error tracking and monitoring features. Including the ability to see all except in one place, identifying unique errors, quicking finding new errors after a deployment, email notifications about new errors, and much more.

Stackify’s error and log management tool can help you easily monitor and troubleshoot your application.

When should i use try catch php?

Summary

In this tutorial, we showed how to use PHP try catch blocks. We also covered some advanced uses with multiple exception types and even how to log all of your errors to a logging library. Good error handling best practices are critical to any PHP application. Retrace can help you quickly find and troubleshoot all of the exceptions being thrown in your code.

  • About the Author
  • Latest Posts

When should you use try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

When should we use try catch?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Can we use try without catch in PHP?

You must use catch with try . Please look php.net manual. PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP.

Why is exception handling used in PHP?

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: The current code state is saved.