Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use multiple PHP Exception classes

Tags:

exception

php

I admit I do not use Exceptions a whole lot and they are at time hard for me to grasp 100% in PHP, this could be partially because PHP does not have the best error => Exceptions support but none the less I do not know much about them.

Take for example this code below, it has 4 different Classes defined that do nothing but extend a base Exception class. I am just curious why one would not just call an Exception and why they have all these separate classes.

I assume there is a good reason?

class OptimizeImageException extends Exception {};

class FileNotFoundException extends OptimizeImageException {};

class FileNotImageException extends OptimizeImageException {};

class ModuleNotFoundException extends OptimizeImageException {};
like image 457
JasonDavis Avatar asked Feb 22 '23 22:02

JasonDavis


1 Answers

By having multiple Exception classes, you can pick out which one you're interested in when catching them.

<?php                                                                       
class OptimizeImageException extends Exception {};

class FileNotFoundException extends OptimizeImageException {};

class FileNotImageException extends OptimizeImageException {};

class ModuleNotFoundException extends OptimizeImageException {};

try {
  throw new FileNotImageException();
} catch (FileNotFoundException $x) {
  echo "NOT FOUND!";
  // do something about it
} catch (FileNotImageException $x) {
  echo "NOT IMAGE!";
  // do something about it
} catch (Exception $x) {
  echo "UNKNOWN EXCEPTION!";
  // do something else about it
}

This is a trivial example, but say you have a function loadImage() which is supposed to load an image. If the function fails, you can handle different failure scenarios differently. If you always throw a basic Exception, you only know something went wrong. You don't know what went wrong, so you can't have different recovery responses based on different scenarios, not without using another mechanism (which then makes exceptions rather weak).

like image 55
Amadan Avatar answered Feb 24 '23 12:02

Amadan