Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php. why are there exceptions of different classes? ex: PDOException vs Exception?

Ok. very much totally noob question but I really don't have a clue and couldn't find a definitive answer:

Why there are different exception classes? For exemple: PDOException vs Exception? the way it goes through my brain: if something wrong happened in the code - exception will be thrown - right? why does it matter what type of exception?

example:

try {
     some code
}
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

vs Exception class:

try {
     some code
}
catch(Exception $e)
    {
    echo $e->getMessage();
    }

Thanks:)

like image 817
Stann Avatar asked Mar 01 '11 08:03

Stann


1 Answers

Because you should not treat all exception in the same way.

If you catch an exception, you could/should display an error message. But you could/should do some other things. And it will depend of the kind of exception you received.

If there is no db connection -> display message

If a query failed -> display a message and maybe do a rollback

...

Finally, you should catch all kind of exception and the last one should be Exception

try {
 some code
}
catch(PDOException $e)
{
    echo $e->getMessage();
    // Do something
}
catch(XYZException $e)
{
    echo $e->getMessage();
    // Do something different
}
catch(Exception $e)
{
echo $e->getMessage();
}
like image 140
j_freyre Avatar answered Oct 09 '22 01:10

j_freyre