Reputation: 1394
When a generic exception is thrown in your application, you have to read through the stack trace to determine where and what caused that exception to be thrown.
(...) By custom exceptions, we’ve made it easy to identify from which part of our application the exception comes from.
I don't get it. With default Exception stack trace indicates me line where exception was originally thrown.
function foo($i)
{
if ($i<0){
throw new Exception("<0");
}
if ($i>0){
throw new Exception(">0");
}
}
try {
foo(1);
} catch (Exception $e) {
throw $e;
}
So how do custom Exceptions facilitate the identification?
Upvotes: 1
Views: 22
Reputation: 311338
With a generic exception like Exception
, you'll have to read through the stack trace to understand what's going on. Custom exceptions can convey this information in their type, allowing you to programatically address the issue:
function foo($i)
{
if ($i<0){
throw new NegativeInputException($i);
}
if ($i>0){
throw new PositiveInputException($i);
}
}
try {
foo(getFromUser());
} catch (NegativeInputException $e) {
echo "why would you input a negative number?";
} catch (PositiveInputException $e) {
echo "why would you input a positive number?";
}
Upvotes: 1