用户定义的例外:我们何时使用它们?什么是“例外”情况? [英] User defined exceptions: when do we use them? What is an "exceptional" situation?

查看:196
本文介绍了用户定义的例外:我们何时使用它们?什么是“例外”情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这个问题已在许多最佳实践书籍中得到解决,但仍然... ... b $ b大多数时候我看到错误使用自定义异常的例子,因此我想知道什么是使用它们的好情况?

I'm sure that this question has been addressed in many best practices books, but still... Most of the times I see examples of wrong usage of custom exceptions, therefore I was wondering what would be a good situation to use them?

特别是,目前我正在为编译器课程开发类型检查器。因此,我有一个SymbolTable类,它是与普通地图非常相似。与普通地图的主要区别在于每个符号最多只能定义一次,因此如果我们尝试插入的密钥已经存在,则put(String,Object)操作应该会失败SymbolTable。

In particular, at the moment I'm working on a type checker for a compilers course.Therefore, I have a SymbolTable class, which is rather similar to a Map.The key difference from your ordinary map is that each symbol has to be defined at most once, so a put(String, Object) operation should fail if the key we're trying to insert is already present in the SymbolTable.

所以这就是问题:每当我们尝试插入一个密钥,并且该密钥已经存在于SymbolTable中时,SymbolTable应该如何表现?我们应该有一个

So here's the question: whenever we try to insert a key, and that key already exists in the SymbolTable, how should the SymbolTable behave? Should we have a

boolean insert(String key, Object value);

在插入失败的情况下返回false的方法?或者我们应该使用插入方法有一个返回值void并在遇到重复值时抛出异常?

method that returns "false" in case the insert fails?Or should we rather use an insert method that has a return value "void" and throws an exception when a duplicate value is encountered?

提前致谢:)

推荐答案

例外情况应该是特殊情况

在这种特殊情况下,例如,如果方法名为 insert()我会将列表密钥上的视为正常情况并更新它。

In that particular case, for example, if method is named insert() I would treat an already on the list key as a normal case and update it.

此外,虽然不应该使用异常来控制代码流,但是返回布尔值指示失败/成功也不是更好的选择(可能有很多情况下失败,False表示什么都没有关于此事。)

Moreover, although exceptions shouldn't be used to control the code flow, return booleans indicating failure/success isn't the better option either(there can be many cases for failure and False indicates nothing on the matter).

底线,我会做一些事情:

Bottom line, I would do something line this:

// Failures can happen 
void add(key, value) throws AlreadyOnMapException

// Update if already on list
void insert(key, value);

// Make available Contains() methods to control the flow by avoiding exceptions
boolean containsKey(key);

boolean containsValue(value);

这篇关于用户定义的例外:我们何时使用它们?什么是“例外”情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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