Java 相当于 .NET System.InvalidOperationException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3381322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:34:25  来源:igfitidea点击:

Java equivalent to .NET System.InvalidOperationException

javaexception

提问by Sergio Acosta

I am not as familiar with Java's exception packages as with those of .NET. I'm in a situation where, if programming in C#, I would throw a System.InvalidOperationException.

我对 Java 的异常包不像对 .NET 的那些包那么熟悉。我的情况是,如果用 C# 编程,我会抛出一个System.InvalidOperationException.

Before creating my own java.lang.RuntimeExceptionsubclass, I need to know if there is a similar exception type I should throw in Java.

在创建我自己的java.lang.RuntimeException子类之前,我需要知道是否有类似的异常类型应该在 Java 中抛出。

The exact scenario is:

确切的场景是:

My class is a value object that provides an int intValue()method, returning an int. However, in some situations, the current value cannot be provided as an int, so this class also provides a boolean isInteger()to allow API users to know when intValue()can be safely invoked.

我的类是一个值对象,它提供了一个int intValue()方法,返回一个 int。但是,在某些情况下,当前值不能以 int 形式提供,因此该类还提供了一个boolean isInteger()让 API 用户知道何时intValue()可以安全调用。

If a caller calls intValue()when isInteger()is false, an exception should be thrown.

如果调用者调用intValue()when isInteger()is false,则应抛出异常。

And the question is: What type of exception?

问题是:什么类型的异常?

I know that this question might not have a correctanswer, but considering that I don't have lots of experience designing Java APIs, I want to know from other Java developers what they would expect to be thrown in this scenario.

我知道这个问题可能没有正确答案,但考虑到我没有很多设计 Java API 的经验,我想从其他 Java 开发人员那里知道他们希望在这种情况下抛出什么。

thanks

谢谢

回答by Jon Skeet

Throw an IllegalStateException:

扔一个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.

表示在非法或不适当的时间调用了方法。换句话说,Java 环境或 Java 应用程序未处于所请求操作的适当状态。