Are exceptions in php really that useful?

后端 未结 9 2312
猫巷女王i
猫巷女王i 2021-02-08 14:48

3 days ago I started rewriting one of my scripts in OOP using classes as a practice after reading a lot about the advantages of using OOP.

Now I\'m confused weather I sh

9条回答
  •  攒了一身酷
    2021-02-08 15:23

    If I understand how you're doing it, I think you're doing it wrong. Exceptions for not for errors. They are for exceptional circumstances. Errors can mean any number of things (for example, a user didn't enter a long enough user name on a registration form). That itself shouldn't be an exception. You could however use an exception to show that registration itself failed (Depending on the situation)...

    And you don't need to have a try/catch block at every level. In fact, that's bad practice. Only catch exceptions if you either can handle the exception, or need to do something else before letting the exception continue. So, for example: If you are connecting to a remote set of websites, and the first one fails. You can catch the exception for that one, and retry with a second website. And keep going until you have no more left (at which point you'd throw another exception to indicate that no websites could be fetched). Another example would be if you're generating images. You have a method that does some computation while generating the image that throws an exception. You'll want to catch that exception so that you can "clean up" from the image process (to save memory, etc) and then re-throw it once you're done: catch (ImageSomethingException $e) { /* Clean up here */ throw $e; }...

    The true power of exceptions is that it lets you handle the situations however you want (since the exception can just bubble up to the top of the program). But only catch exceptions where you know you can deal with them (or at least need to clean up). You should almost never do print $e->getMessage() inside of production code.

    Personally, I have a default exception handler that I always install. Basically, if an exception is not caught, it will log that exception and then generate a 500 error page. That lets me focus on what exceptions I can deal with in code instead of trying to catch everything (which isn't usually a great idea)...

    Good luck...

提交回复
热议问题