PHP why are there exceptions from different classes? ex: PDOException vs Exception?

Ok a very complete question about noob, but I really have no clue and did not find a definitive answer:

Why are there different exception classes? For example: PDOException vs Exception? how it passes through my brain: if something happened in the code - an exception will be thrown - right? why what type of exception matters?

Example:

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

vs Exception Class:

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

Thank:)

+3
source share
6 answers

Because you do not have to handle all exceptions in the same way.

If you catch an exception, you may / should display an error message. But you could / should have done something else. And that will depend on the type of exception you are getting.

db →

→ , ,

...

, , 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();
}
+7

. . PDO PDO errorInfo: http://www.php.net/manual/en/class.pdoexception.php#pdoexception.props.errorinfo

Exception, .

, , try/catch , . , , , , catch. , , ; "" catch :

try {
    // ... code
} catch (ConnectionException $e) {
   // try to reconnect
} catch (Exception $e) {
   // log exception
}

. ConnectionException - , , - , .

+3

.

try {
  do_something();
} catch (PDOException $e) {
  echo "PDO failed";
} catch (Exception $e) {
  echo "Unknown component failed";
}

"catch-all" -expression ( , : " " ), "", -exception, .

+1

- :

  • PDOException, SQL-.
  • RuntimeException SplFileObject, , .
  • ...

, PHP , 99% ( ), .

+1

, ( try/catch) , , , . , , .

: , /, , , .

It allows you to structure error handling.

+1
source

Exceptions can have different logic. For example, not all exceptions should be fatal. Some exceptions will allow you to resume work after searching for them.

Each class must have its own exception handler.

  • because every class implementation is different. And the logic of errors / exceptions.
  • This way you can easily track which package / class throws an exception.
+1
source

Source: https://habr.com/ru/post/1795430/


All Articles