Z
Z
Zohei2015-08-17 15:05:48
Yii
Zohei, 2015-08-17 15:05:48

PHP/Yii2 how to properly handle exceptions?

I admit, I'm a noob when it comes to working with exceptions. Previously, for the most part, I did without them, but now I want to figure it out.
Why PHP has two base classes \Exception and \ErrorException?
Why does Exception catch Unknown Property Exception but not, say, division by 0?? And in ErrorException exactly the opposite?

try {
  $myClass->myUnknowProperty;
  //10/0; //error!!!1
  // throw new \ErrorException ("tralala"); // error!!!
} catch (\Exception $e) { 
  log("warning UnknowProperty");
}

try {
  //$myClass->myUnknowProperty; //error!!
  10/0;
  //throw new \Exception("tralala"); // error!!
} catch (\ErrorException $e) { 
  log("warning division by zero");
}

My goal, in case of an error, is to log it and show the page to the user, albeit with some bugs, but not to throw it on the server error.
How do you catch exceptions?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Z
Zohei, 2015-08-17
@Zohei

Why does Exception catch Unknown Property Exception but not, say, division by 0?? And in ErrorException exactly the opposite?

this is all partly due to inattention:
catch \Exception catches exceptions perfectly, but I tried to catch exceptions with the \yii\base\Exception class =(

A
Alexander Masterov, 2015-08-17
@AlexMasterov

Recently, a good article on this topic was published on Habré, with examples for Yii:
Proper use of Exceptions in PHP .

P
Paulus, 2015-08-18
@ppokrovsky

ErrorException is used for example when you want to turn a PHP error message into an exception,
see set_error_handler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question