简体   繁体   中英

Should a stand-alone PHP class throw exceptions?

I'm currently building a stand-alone PHP class to wrap the Instagram API with a few custom code for the types of projects I work on at my company. As I develop my code, I often find myself writing sutff like this:

if (!$this->accessToken)
    throw new Exception("Instagram: Access Token can't be NULL", 1);

Is this a bad practice? If so, what's the recommended approach to situations like these?

This is good practice, as it allows people using your library to handle errors properly. It's always a good idea to throw an exception when an exceptional circumstance occurs (such as important values being null).

The only improvement I could suggest to use a more specific exception class. For this case, you might want to throw an InvalidArgumentException or UnexpectedValueException . Using a more specific exception class means that people can check more specifically for that class in catch blocks. For more complex applications defining your own exception classes to handle specific exceptions types is a good idea.

Also, it's very helpful for people using IDEs if you annotate the methods which throw exceptions with @throws tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM