Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Toptal.com:
Clean Code and The Art of Exception Handling
Apr 13, 2016 @ 14:43:50

While not specific to PHP (the examples are in Ruby, in fact) this new tutorial on the Toptal.com blog has some good information and suggestions around the use of exceptions in your applications.

Exceptions require special treatment, and an unhandled exception may cause unexpected behavior. The results are often spectacular.

Over time, these errors, and countless others [...] contributed to the impression that exceptions are bad. But exceptions are a fundamental element of modern programming; they exist to make our software better. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable.

They start by talking about why exception handling is a good thing and some common practices to help make them more manageable. They suggest that good exception handling can also help make your code more maintainable, extensible and readable in the long run. He suggests creating your own kind of exception hierarchy (more possible in PHP 7) and using them to get more specific on the type of exception that was thrown. He recommends not "rescuing" exceptions more than needed (in PHP this is try/catch) and that it's okay to defer the handling for the exception being thrown and not deal with it right away.

He also reminds you that not all exceptions need handling in your own code (sometimes it's up to the user) and that following conventions on naming can help end users better understand why there's an error. Finally, he recommends logging exceptions as they're major errors in your application, not just data problems or smaller bugs.

tagged: clean code exception handling bestpractice hierarchy trycatch convention

Link: https://www.toptal.com/qa/clean-code-and-the-art-of-exception-handling


Trending Topics: