抛出什么异常-&“错误场景&"(Java) [英] What exception to throw - "Wrong Scenario" (Java)

查看:46
本文介绍了抛出什么异常-&“错误场景&"(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个愚蠢的问题-但这使我感到烦恼.
从现有的(库)Java异常中,应该在以下内容中提出.
我有一种在错误情况下使用的方法(它的基本假设不成立).
此方法没有参数-因此,我倾向于跳过 IllegalArgumentException .

This is a silly question - but it bugs me.
From the existing (library) Java exceptions, which should I throw in the following.
I have a method that is used in the wrong scenario (it's basic assumption doesn't hold).
This method has no arguments - so I tend to skip the IllegalArgumentException.

作为一个例子-考虑一个只有两个左/右子节点的 BinaryNode 类.

As an example - consider a BinaryNode class having just two left/right child nodes.

为简便起见,最好有一个 removeOnlyChild()方法,该方法仅在该节点实际上只有一个孩子(而不是0或2)时才适用.显然,如果有人在具有两个子节点的节点 n 上调用 n.removeOnlyChild(),则应引发异常.
在标准Java异常之外-您认为应该是哪个异常,为什么?

For brevity it's nice to have a removeOnlyChild() method, which applies only if this node actually has just one child (not 0 or 2).
Obviously if someone calls n.removeOnlyChild() on a node n that has 2 children, an exception should be thrown.
Out of the standard Java exceptions - which do you think it should be, and why?

实际上,我每次都要遍历该列表,当弹出时,只需使用

I'm actually going over the list every-once-in-a-while, when this pops-up, and just go with IllegalStateException or with InternalError.

推荐答案

我有一种用于错误场景的方法(它的基本假设不成立).

I have a method that is used in the wrong scenario (it's basic assumption doesn't hold).

这听起来与 完全匹配IllegalStateException :

That sounds like an exact match for IllegalStateException:

表示已在非法或不适当的时间调用了一种方法.

Signals that a method has been invoked at an illegal or inappropriate time.

诚然,时间"部分会让人产生误解,但是给定名称,将其含义扩展到当对象处于该调用的不适当状态时已调用方法"似乎是合理的.您的用法类似于 Iterator.remove() 如果迭代器在第一个元素之前或已删除当前"元素,则抛出 IllegalStateException .

Admittedly the "time" part feels a little misleading, but given the name it seems reasonable to extend the meaning to "a method has been invoked when the object is in an inappropriate state for that call". Your use is similar to that of Iterator.remove() which throws IllegalStateException if the iterator is before the first element or has already removed the "current" element.

我肯定会在 InternalError ,用于处理虚拟机错误,而不是应用程序代码错误.

I'd definitely go with that over InternalError which is for Virtual Machine errors, not application code errors.

这篇关于抛出什么异常-&“错误场景&"(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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