On this submit, you will learn to use exception dealing with in PHP. As of PHP 5, we are able to use attempt catch blocks for error dealing with—it is a higher approach to deal with exceptions and management the stream of your software. On this article, we’ll undergo the fundamentals of exception dealing with together with a few real-world examples.
What’s an Exception?
PHP 5 launched a brand new error mannequin which lets you throw and catch exceptions in your software—it is a higher method of dealing with errors than what we had in older variations of PHP. All exceptions are situations of the bottom class
Exception, which we are able to lengthen to introduce our personal customized exceptions.
It is necessary to notice right here that exception dealing with is totally different than error dealing with. In error dealing with, we are able to use the
set_error_handler operate to set our customized error dealing with operate in order that at any time when an error is triggered, it calls our customized error dealing with operate. In that method, you possibly can management errors. Typically nonetheless, sure sorts of errors are unrecoverable and cease program execution.
However, exceptions are one thing which can be thrown intentionally by the code, and it is anticipated that it will be caught sooner or later in your software. So we are able to say that exceptions are recoverable versus sure errors that are unrecoverable. If an exception which is thrown is caught someplace in your software, program execution continues from the purpose the place the exception was caught. And an exception which isn’t caught wherever in your software ends in an error, thus halting program execution.
Exception Dealing with Management Move
Let’s discuss with the next diagram that exhibits the generic exception dealing with management stream.
Exceptions might be thrown and caught through the use of the
catch blocks. You might be answerable for throwing exceptions when one thing happens which isn’t anticipated. Let’s shortly undergo the essential exception dealing with stream as proven within the following pseudo code.
// code earlier than the try-catch block attempt catch (Exception $e) // code after the try-catch block, will all the time be executed
More often than not, once you’re coping with exceptions, you will find yourself utilizing a sample as proven within the above snippet. You can even use the
lastly block together with the
catch blocks, however we’ll get again to that later on this article.
attempt block is the one to make use of the place you observed that your code might generate an exception. It is best to all the time wrap such code utilizing
Throwing an Exception
An exception is likely to be thrown by a operate that you just name, or you possibly can use the
throw key phrase to throw an exception manually. For instance, you may validate some enter earlier than performing any operation, and throw an exception if the info shouldn’t be legitimate.
It is necessary to notice right here that should you throw an exception however you have not outlined the
catch block which is meant to deal with that exception, it will end result within the deadly error. So you have to just remember to all the time outline the
catch block should you’re throwing exceptions in your software.
As soon as an exception is caught within the
catch block, the
Exception object accommodates the error message which was thrown utilizing the
throw key phrase. The
$e variable within the above instance is an occasion of the
Exception class, so it has entry to all strategies of that class. On this block, you need to outline your personal exception dealing with logic—what precisely you wish to do with the error you catch.
Within the subsequent part, we’ll undergo a real-world instance to grasp how exception dealing with works.
A Actual-World Instance
On this part, we’ll construct a real-world instance to display exception dealing with in PHP.
Let’s assume that you have constructed an software which masses software configuration from the config.php file. Now, it is important that the config.php file should be current when your software is bootstrapped. Thus, your software cannot run if the config.php file shouldn’t be current. So that is the proper use-case to throw an exception and let the person know they should repair the difficulty.
<?php attempt catch (Exception $e) ?>
As you possibly can see within the above instance, we’re checking for the existence of the config.php file at first of the bootstrapping part. If the config.php file is discovered, the execution is sustained usually. However, we’ll throw an exception if the config.php file would not exist. Additionally, we wish to cease execution as effectively in case there’s an exception!
In order that’s how you need to use exceptions in your functions. It is best to throw exceptions for use-cases which can be distinctive—you should not unnecessarily throw exceptions for generic errors like invalid person credentials, improper listing permissions and many others., that you just anticipate to occur regularly. These are higher dealt with by generic error messages within the common software execution stream.
In order that was an instance of dealing with exceptions utilizing the default
Exception class. Within the subsequent part, we’ll see how one can lengthen the core
Exception class and create your personal customized exceptions in your software.
Methods to Create Customized Exceptions
On this part, we’ll talk about how one can create customized exceptions in your functions. Actually, we’ll lengthen the instance which we have simply mentioned within the earlier part to display customized exceptions.
Within the earlier instance, we threw the configuration exception utilizing the default
Exception class. That is completely wonderful so long as you simply wish to cope with the exception error message. Nonetheless, generally you wish to do a bit extra primarily based on the kind of exception which is being thrown. That is the place customized exceptions are helpful.
Let’s revisit the earlier instance as proven within the following snippet.
<?php class ConfigFileNotFoundException extends Exception attempt catch (ConfigFileNotFoundException $e) catch (Exception $e) ?>
Firstly, we have outlined the
ConfigFileNotFoundException class which extends the default
Exception class. Now, it turns into our customized exception class and we are able to use it after we wish to throw the
ConfigFileNotFoundException exception in our software.
Subsequent, we have used the
throw key phrase to throw the
ConfigFileNotFoundException exception in case the config.php file would not exists. The necessary distinction lies within the
catch block although. As you possibly can see, we have outlined two
catch blocks, and every block is used to catch the totally different sort of exception.
The primary one catches exceptions of the
ConfigFileNotFoundException sort. So, if an exception which is being thrown is of the
ConfigFileNotFoundException sort, this block will likely be executed. If the exception sort would not match any of the precise
catch blocks, it’s going to match the final one which is there to catch all generic exception messages.
The Lastly Block
On this part, we’ll how you need to use the
lastly key phrase together with the
catch blocks. Typically, you wish to execute a bit of code regardless of whether or not an exception was thrown. That is the place you need to use the
lastly block, for the reason that code you place within the lastly block will all the time be executed after execution of the attempt to catch blocks, regardless of whether or not or not an exception has been thrown.
Let’s attempt to perceive it utilizing the next instance.
attempt catch (Exception $e) lastly
The code within the above instance is just about the identical with the one exception that we have added the
lastly block after the
catch block. And as we mentioned, the code on this block will all the time be executed.
The standard use-cases that we may consider utilizing the lastly block are usually associated to useful resource cleanup. For instance, should you’ve opened a database connection or a file on the disk within the
attempt block, you possibly can carry out cleanup duties like closing the connection within the
lastly block because it’s assured to run.
Exception dealing with is a key coding ability and you need to take into account how exceptions will likely be dealt with whereas growing your functions. This may allow you to detect and get better from sudden errors in your software. I hope that this submit will encourage you to write down higher error dealing with code!
As we speak, we mentioned the subject of exception dealing with in PHP. Within the first half of the article, we mentioned the fundamentals of exceptions in PHP and constructed a real-world instance to display how they work. On the finish, we explored how one can create customized exceptions by extending the core