抛出什么例外 - “错误的场景” (JAVA) [英] What exception to throw - "Wrong Scenario" (Java)

查看:133
本文介绍了抛出什么例外 - “错误的场景” (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() c $ c>有2个孩子,应该抛出一个例外。

除了标准的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?

我实际上是在一次一次的时候,当这个弹出窗口,并且只是与 IllegalStateException InternalError

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天全站免登陆