Understanding Try / Catch

Various times in history I tried to get my head around understanding when to use try/catch and when not to use it. Sometimes it’s just good to discuss it with your colleagues if you fail to properly understand the concept. Maybe they are able to fill in the missing parts.

So the question I always had is, when to use try/catch and when not.

Lets say you have a piece of code which throws an exception:

Class Car {
   public function __construct($name)
if ($name = 'audi’){
throw new NotExistException();

Now when you instantiate this new class like this:

$audi = new Car('Audi') 

Your application will actually crash and your users will notice this.

But lets say you don’t want your application to crash because it is perfectly fine to create a different car like a Fiat or a Mercedes. But when an Audi is created you want to get some type of warning or log message. As opposed to let your application crash.

In this case the way to go would be:

$cars = ['Audi','Fiat', 'Mercedes'];
foreach ($cars as $car){
$vehicle = new Car($car);
} catch(NotExistException $e){

In this case, when we try to create the Audi, we will get an exception. The exception will be logged but the application will continue to execute. And this is very often what you want. After the exception was caught we will continue and create the other cars.

So if you don’t catch the exception the the exception will be bubbled up. Then the error handler will eventually take care of the exception.