开发者

Appropriate use of exceptions?

We are developing a collection class for a specialized PHP application. In it, there are functions named map, each, etc.

A debate has been brought up about calling some functions with a bad argument. For example:

public function each($fn) {
    // ...
}

// ...

$collection->each('not a function');

Should the call to each throw an exception? Should it return null? Should we ignore开发者_JAVA百科 the bad argument and let the runtime error when an attempt is made to call the nonexistant function? I'm not sure how we should handle this case.


exceptions are for exceptional situations, not bad coders.

Use assertions instead. See http://php.net/manual/en/function.assert.php

If this is for a library for external use, then exceptions on exposed methods may make sense, (e.g. InvalidArgumentException) but, in general, assertions are more appropriate for verifying internally that your code meets your required conditions.

Perhaps another example will help clarify things, a good use of an exception is when doing file access and as there is some possibility that the resource will not be accessible due to a downed server, etc.

Also see Design by contract using assertions or exceptions?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜