A Practical Guide on Writing Exceptionally Good Exceptions [ in PHP ]

By: Sunil Kumar |  In: PHP  |  Last Updated: 2020/03/29

A Practical Guide on Writing Exceptionally Good Exceptions [ in PHP ]

Sorry to say but its nearly impossible to write a bug-free application. Especially when you are working on a large scale application. You cannot test the application in all the ways a user is going to interact with.

But what you can do is you can handle all the possible cases and write exception for the rest of the case. So that you can check for any unusual behavior of the program.

Before going straight to the best practices you need to know how PHP exception actually works. to understand this let’s take an example

function setName($name) {
  if(is_null($name))
   throw new Exception("name cannot be null");
 $this->name = $name;
}

try {
   setName($name);
}
catch(Exception $e)
{
   echo 'Message ' . $e->getMessage(); 
}
finally{
  //this code is always executed if an exception take place. you can use this block to close the database connection or closing a file etc.
}

In this example, you can see that inside try block we have called a function setName(). if we pass a null value to the $name parameter it will throw an exception as written in the setName function definition and catch block will catch this exception and echo the error.

try catch exception handling php

Writing a good exception handling is also need mastering in it when you are working on a complex application.

So here I am listing some of the best practices I follow while handling exceptions –

Provide a meaningful message in the Exception

The correct message is the thing that is going to help you to find the issue. Without a proper message, you will see some error without any idea what is this all about.

For example, let’s see these two exception messages-

example #1

try { 
   something(); 
} catch (Exception $ex) {
   return "invalid value - {$value} passed for the  argument - {$argument}";
}

example #2

try {
   something();
} catch (Exception $ex) {
   return "invalid value passed";
}

You can clearly see that message1 is a generic message and no one will find that what invalid value is passed and for which argument. while message2 clearly stating that the invalid value passed for which argument. This makes the

Use standard exception

You should be using the PHP standard exception. Using standard exception make your code more readable, and maintainable because almost everyone will be familiar with the standard exception like BadFunctionCallException, OutOfBoundsException, OutOfRangeException.

Another benefit of using standard exception is anyone can understand the purpose of the exception just having a look on the code instead of looking for other docs or reading the code thoroughly.

Don’t show the exception to the user

Never show the exception message to the end-user until you are not working on any library. Because the user never be understanding the error message. Also, you are revealing your directory structure to the user knowingly which you never want to do.

The user should get a general failure message instead.

But if you are working on a library it becomes essential to throw a proper exception so that the developer who is integrating the library can understand what he/she is doing wrong and can debug easily.

Do not catch everything

You should not be interested in catching an exception if you cannot handle it or cannot do anything about it.

Always keep in mind that a coworker who doesn’t know your code (or maybe yourself in a few months) may need to call the method and handle the exception.

The one important rule about catching exceptions is that you should never just swallow all exceptions silently… e.g. something like this-

try { 
    something(); 
} catch (Exception ex) {

}

Because these can be some of the hardest issues to track down. A good trick is to know when to catch an exception is – you should be catching exception only when you can deal with it.  If you cannot handle the exception completely then you should let it bubble up.

Log the exception

Keeping a log of exceptions and errors is a good habit. It helps you to go after the issue later as well.  You should be logging as much information as possible but the messaging needs to be clear as mentioned earlier.

Use multiple catch statements

PHP supports multiple catch blocks within a single try block.

try {
   // your code here
}
   catch (OverflowException $ex) {
   echo $ex->getMessage();
}
catch (Exception $ex) {
   echo $ex->getMessage();
}

This helps to create clear messaging and return a more understandable error message. I recommend using a global catch block while using a specific exception catch block if you are unsure about the exception type the code can throw.

 

These are some practices I follow while writing exception in any application and these help me a lot to track the issue. If you have any suggestions for writing better exceptions, for the reader please let the readers know.

 

Comments


Leave a Comment

Your email address will not be published.

*


%d bloggers like this: