Java 中是否有与 C# 的 InvalidOperationException 等效的方法?
我正在将一些 C# 代码转换为 Java,并且需要包含一个类似于 C# 的 InvalidOperationException 的异常。这样的事存在吗?还有两种语言中等效的异常类型列表吗?谢谢。
I think in my particular case IllegalStateException is most appropriate. Thanks for all the responses.
I'm converting some C# code to Java and I need to include an exception that is similar to C#'s InvalidOperationException. Does such a thing exist? Also is there a list of equivalent exception types in the two languages? Thanks.
I think in my particular case IllegalStateException is most appropriate. Thanks for all the responses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是
IllegalStateException
。根据我读到的有关 InvalidOperationException 的内容:“当方法调用对于对象的当前状态无效时引发的异常。”
对于
IllegalStateException
:“表示在非法或不适当的时间调用了方法。换句话说,Java 环境或 Java 应用程序未处于请求操作的适当状态。”根据您使用
InvalidOperationException
的方式,我还可以看到IllegalArgumentException
和UnsupportedOperationException
就是你想要的。前者意味着,一般来说,该方法可以调用,只是这次传递了垃圾;后者意味着该方法永远不适合调用此实例(与IllegalStateException
不同,这意味着有时调用主题方法可能是合适的,只是不适合在片刻)。我不知道一般的 c# <=> Java 异常翻译。
Probably
IllegalStateException
.From what I read about InvalidOperationException: "The exception that is thrown when a method call is invalid for the object's current state."
For
IllegalStateException
: "Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation."Depending on how you are using
InvalidOperationException
, I could also seeIllegalArgumentException
andUnsupportedOperationException
being what you want. The former implies that, in general, the method is fine to call, it was just passed garbage this time; the latter implies that the method is never appropriate to call for this instance (unlikeIllegalStateException
, which implies that it might be appropriate to call the subject method sometimes, just not at the moment).I am not aware of a general c# <=> Java translation of exceptions.
Petar 向我指出了这个示例代码(来自 msdn),
因此在这种情况下您可以使用 IllegalStateException,尽管它说:
非法虚拟机状态绝对不是上述参考示例中的问题。这里的问题是该对象无效,因为它引用了只读日志文件。
我自己的建议:只需像
我一样定义一个自定义异常,这比尝试从
java.lang
包中找到最合适的异常要容易得多。Petar pointed me to this example code (from msdn)
So in this context you could use an IllegalStateException, although it says:
And an illegal VM state is definitly not the issue in the above reference example. Here, the problem is that the object is invalid, because it references a read-only logfile.
My own advice: just define a custom exception like
To me, that's much easier then trying to find the best fitting Exception from the
java.lang
package.