Java等效于.NET System.InvalidOperationException [英] Java equivalent to .NET System.InvalidOperationException

查看:80
本文介绍了Java等效于.NET System.InvalidOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉Java的异常包和.NET的异常包。我处于一种情况,如果在C#中编程,我会抛出一个 System.InvalidOperationException



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



确切的情况是:



我的类是一个值对象, int intValue()方法返回一个int。然而,在某些情况下,当前值不能作为int提供,因此此类还提供了一个 boolean isInteger(),以允许API用户知道何时 intValue()可以安全地调用。



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



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



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



谢谢

解决方案

抛出一个 IllegalStateException


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



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.

Before creating my own java.lang.RuntimeException subclass, I need to know if there is a similar exception type I should throw in 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.

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

And the question is: What type of exception?

I know that this question might not have a correct answer, 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.

thanks

解决方案

Throw an 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等效于.NET System.InvalidOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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