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 {};
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With