When to use Exceptions in PHP?

3

I came up with a module of the PHP OOP handout on Handling Exceptions , I practiced the exercises and such, but I'm still not quite sure when to use them, and why. I ran a search and found this:

  

link

and this

  

link

The S-question seemed to me to be more enlightening, as the php doc talks more about 'how to use' Exceptions. The answer that was accepted by @Tower is explanatory, but in the question it describes some code situations where he wanted to know whether or not to use the exceptions, but in the answer he does not use any of the codes used in the question. There is also the @rball response, and there it gives a different notion of exceptions. I would like to hear from you, when I should use them, and if possible, explain each situation proposed by the question quoted.

ps: I know there is an identical question, but the answer has been translated from the question I quoted up there ^, and as I said, the response that @Tower accepted does not describe the use of Exceptions in the codes it gave for example.

ps2 .: ELI5 (Explain Like I'm Five / Me explains as if I were a 5 year old)

    
asked by anonymous 10.02.2016 / 23:41

1 answer

2

I usually use whenever a data input error happens, or when something is expected to exist and this something does not exist, whenever your logic can be broken, then you raise an exception.

More important than using exceptions, I think I know how to position the try-catch block, which can be used with different levels of catch, and also a try-catch block inside another through the layer encapsulation that a structural pattern can generate.

One advantage of using try-catch blocks in different layers is the error control that is most effective, avoiding breaking in upper layers of the application (Controllers), avoiding fatal errors or 500.

Some frameworks implement handlers fault% errors and different exception levels, all extend the same Exception object and are captured at different levels as well.

In case you do not capture, the framework usually tries to identify the exception type and their code to also know how to respond to the request to the user.

Some exception types generate 500, 404, 401 errors, among others.

    
05.03.2016 / 03:51