Try catch in php 7

In this post, you'll learn how to use exception handling in PHP. As of PHP 5, we can use try catch blocks for error handling—this is a better way to handle exceptions and control the flow of your application. In this article, we'll go through the basics of exception handling along with a couple of real-world examples.

What Is an Exception?

PHP 5 introduced a new error model which allows you to throw and catch exceptions in your application—this is a better way of handling errors than what we had in older versions of PHP. All exceptions are instances of the base class

// code before the try-catch block

36, which we can extend to introduce our own custom exceptions.

It's important to note here that exception handling is different than error handling. In error handling, we can use the

// code before the try-catch block

37 function to set our custom error handling function so that whenever an error is triggered, it calls our custom error handling function. In that way, you can control errors. Generally, however, certain kinds of errors are unrecoverable and stop program execution.

On the other hand, exceptions are thrown deliberately by the code, and it's expected that they'll be caught at some point in your application. So we can say that exceptions are recoverable as opposed to certain errors which are unrecoverable. If an exception which is thrown is caught somewhere in your application, program execution continues from the point where the exception was caught. And an exception which is not caught anywhere in your application results in an error, thus halting program execution.

Exception Handling Control Flow

Let's refer to the following diagram that shows the generic exception handling control flow.

Try catch in php 7
Try catch in php 7
Try catch in php 7

Exceptions can be thrown and caught by using the PHP 

// code before the try-catch block

38 and
// code before the try-catch block

39 blocks. You are responsible for throwing exceptions when something occurs which is not expected. Let's quickly go through the basic exception handling flow, as shown in the following pseudo-code.

1
// code before the try-catch block

2
 
3
try {
4
  // code

5
 
// code before the try-catch block

0
// code before the try-catch block

1
// code before the try-catch block

2
// code before the try-catch block

3
// code before the try-catch block

4
 
// code before the try-catch block

6
// code before the try-catch block

7
// code before the try-catch block

8
// code before the try-catch block

9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
 
2
8
2
9

Most of the time, when you're dealing with exceptions, you'll end up using a pattern, as shown in the above snippet. You can also use the

// code before the try-catch block

40 block along with the
// code before the try-catch block

38 and
// code before the try-catch block

39 blocks, but we'll get back to that later in this article.

The

// code before the try-catch block

38 block is the one to use where you suspect that your code may generate an exception. You should always wrap such code using
// code before the try-catch block

38 and
// code before the try-catch block

39. 

Throwing an Exception

An exception might be thrown by a function that you call, or you can use the

// code before the try-catch block

46 keyword to throw an exception manually. For example, you might validate some input before performing any operation, and throw an exception if the data is not valid.

It's important to note here that if you throw an exception but you haven't defined the

// code before the try-catch block

39 block which is supposed to handle that exception, it'll result in a fatal error. So you need to make sure that you always define the
// code before the try-catch block

39 block if you're throwing exceptions in your application.

Once an exception is caught in the

// code before the try-catch block

39 block, the
// code before the try-catch block

36 object contains the error message which was thrown using the
// code before the try-catch block

46 keyword. The
// code before the try-catch block

52 variable in the above example is an instance of the
// code before the try-catch block

36 class, so it has access to all methods of that class. In this block, you should define your own exception handling logic—what exactly you want to do with the error you catch.

In the next section, we'll go through a real-world example to understand how exception handling works.

A Real-World Example

In this section, we'll build a real-world example to demonstrate exception handling in PHP.

Let's assume that you've built an application which loads the application configuration from the config.php file. Now, it's essential that the config.php file is present when your application is bootstrapped. Thus, your application can't run if the config.php file is not present. So this is the perfect use case to throw an exception and let the user know they need to fix the issue.

1
 
1
2
try {
3
 
5
4
 
5
 
9
// code before the try-catch block

0
 
// code before the try-catch block

2
3
3
// code before the try-catch block

4
3
5
// code before the try-catch block

6
3
7
// code before the try-catch block

8
3
9
2
0
try {
1
2
2
try {
3
2
4
// code before the try-catch block

9
2
6
try {
7
2
8
try {
9
4
0
2
5
4
2
4
3

As you can see in the above example, we're checking for the existence of the config.php file at the beginning of the bootstrapping phase. If the config.php file is found, the execution continues normally. On the other hand, we'll throw an exception if the config.php file doesn't exist. Also, we would like to stop execution if there's an exception!

So that's how you can use exceptions in your applications. You should throw exceptions for use cases that are exceptional—you shouldn't unnecessarily throw exceptions for generic errors like invalid user credentials, improper directory permissions, etc., that you expect to happen frequently. These are better handled by generic error messages in the regular application execution flow.

So that was an example of handling exceptions using the default

// code before the try-catch block

36 class. In the next section, we'll see how you can extend the core
// code before the try-catch block

36 class and create your own custom exceptions in your application.

How to Create Custom Exceptions

In this section, we'll discuss how you can create custom exceptions in your applications. In fact, we'll extend the example which we've just discussed in the previous section to demonstrate custom exceptions.

In the previous example, we threw the configuration exception using the default

// code before the try-catch block

36 class. That's perfectly fine as long as you just want to deal with the exception error message. However, sometimes you want to do a bit more based on the type of exception which is being thrown. That's where custom exceptions are useful.

Let's revisit the previous example, as shown in the following snippet.

1
 
1
2
4
7
3
 
4
try {
5
 
5
// code before the try-catch block

0
 
// code before the try-catch block

2
 
9
// code before the try-catch block

4
 
// code before the try-catch block

6
3
3
// code before the try-catch block

8
3
5
2
0
5
5
2
2
3
9
2
4
try {
1
2
6
try {
3
2
8
 
3
4
0
 
5
4
2
 
7
 
8
try {
9
// code before the try-catch block

00
// code before the try-catch block

9
// code before the try-catch block

02
try {
7
// code before the try-catch block

04
try {
9
// code before the try-catch block

06
2
5
// code before the try-catch block

08
4
3

Firstly, we've defined the

// code before the try-catch block

57 class, which extends the default
// code before the try-catch block

36 class. Now, it becomes our custom exception class, and we can use it when we want to throw the
// code before the try-catch block

57 exception in our application.

Next, we've used the

// code before the try-catch block

46 keyword to throw the
// code before the try-catch block

57 exception if the config.php file doesn't exist. The important difference lies in the
// code before the try-catch block

39 block, though. As you can see, we've defined two
// code before the try-catch block

39 blocks, and each block is used to catch a different type of exception.

The first one catches exceptions of the

// code before the try-catch block

57 type. So, if an exception which is being thrown is of the
// code before the try-catch block

57 type, this block will be executed. If the exception type doesn't match any of the specific
// code before the try-catch block

39 blocks, it will match the last one, which is there to catch all generic exception messages.

The Finally Block

In this section, we'll how you can use the

// code before the try-catch block

40 keyword along with the
// code before the try-catch block

38 and
// code before the try-catch block

39 blocks. Sometimes, you want to execute a piece of code irrespective of whether an exception was thrown. That's where you can use the
// code before the try-catch block

40 block, since the code you place in the finally block will always be executed after execution of the try and catch blocks, irrespective of whether or not an exception has been thrown.

Let's try to understand it using the following example.

1
try {
2
  // code

3
 
4
// code before the try-catch block

1
5
// code before the try-catch block

3
// code before the try-catch block

0
 
// code before the try-catch block

2
// code before the try-catch block

7
// code before the try-catch block

4
// code before the try-catch block

9
// code before the try-catch block

6
2
1
// code before the try-catch block

8
2
3
2
0
// code before the try-catch block

31
2
2
// code before the try-catch block

33
2
4
2
5

The code in the above example is pretty much the same, with the only exception being that we've added the

// code before the try-catch block

40 block after the
// code before the try-catch block

39 block. And, as we discussed, the code in this block will always be executed.

The typical use cases for the finally block are generally related to resource cleanup. For example, if you've opened a database connection or a file on the disk in the

// code before the try-catch block

38 block, you can perform cleanup tasks like closing the connection in the
// code before the try-catch block

40 block as it's guaranteed to run.

Exception handling is a key coding skill, and you should consider how exceptions will be handled while developing your applications. This will help you detect and recover from unexpected errors in your application. I hope that this post will inspire you to write better error handling code!

Conclusion

Today, we discussed the topic of exception handling using PHP try catch blocks. In the first half of the article, we discussed the basics of exceptions in PHP and built a real-world example to demonstrate how they work. At the end, we explored how you can create custom exceptions by extending the core

// code before the try-catch block

36 class.

Is there a 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.

How to create a try catch in PHP?

Syntax.
<? php..
//try block..
//code that can throw exception..
//catch block..
catch (Exception $e) {.
//code to print exception caught in the block..

What are the errors in PHP 7?

Error hierarchy ¶.
ArithmeticError. DivisionByZeroError..
AssertionError..
CompileError. ParseError..
TypeError. ArgumentCountError..
ValueError..
UnhandledMatchError..
FiberError..

How to catch all PHP errors?

Quickly Show All PHP Errors The quickest way to display all php errors and warnings is to add these lines to your PHP code file: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);