when do I write my own exception class?

后端 未结 4 1194
感情败类
感情败类 2021-02-02 12:00

I have been wondering since I stepped into the murky waters of OOP and have written a couple or so of distributed libraries when it is necessary to write my own extension of the

4条回答
  •  醉话见心
    2021-02-02 12:54

    Only write it when you need it, e.g. to signal an own exception, for example if you code a library and no exception of the existing ones speaks the same.

    See

    1. Core PHP Exceptions
    2. Core PHP SPL Exceptions

    There are a lot of exceptions already build-in in PHP so for the normal program flow things should be covered exception-wise.

    If you're developing a more complex system, like a parser, lexer plus compiler and everything is accessed via one routine/faced for it's API, the parser might want to throw a parser exception, the lexer a lexer exception and the compiler a compiler exception.

    It can be useful to be able to differentiate. But I normally stick with the build in exceptions, it's easy to refactor later anyway in case it needs more differentiation.

    And since there are namespaces nowadays, this is really freaking easy if you stick to the firsthand Exception class from the beginning ;)

提交回复
热议问题