什么时候抛出异常? [英] When to throw exceptions?

查看:164
本文介绍了什么时候抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例外是美妙的事情,但我有时会担心我会抛出太多的东西。考虑这个例子:


类用户{

  public function User(user){

//用户数据查询数据库

如果(!user)抛出新的ExistenceException('User not found');

}

}




我认为简单地返回false(或者在这种情况下将所有用户数据设置为false)是有意义的,而不是抛出异常。



你喜欢哪一个?

解决方案

在特殊情况下抛出异常。

如果条件是程序正常运行时所期望的,请检查并报告错误。对于不应该发生的事情,保留例外情况,或作为向其他程序员发出不可恢复的信息的指示。



在您的情况下,返回 false 更有意义(或者可能使用 null对象作为返回值)。


Exceptions are wonderful things, but I sometimes worry that I throw too many. Consider this example:

Class User {

  public function User(user){

    // Query database for user data

    if(!user) throw new ExistenceException('User not found');

  }

}

I'd argue that it makes as much sense to simply return false (or set all user data to false in this case), rather than throwing an exception.

Which do you prefer?

解决方案

Throw exception in exceptional circumstances.

If the condition is something you expect in the normal run of the program, check for it and report an error. Reserve exceptions for things that should never happen, or as an indication to other programmers that something unrecoverable has occurred.

In your case, returning false makes more sense (or perhaps use a null object as a return value).

这篇关于什么时候抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆