IndexAutoFrangeException(C#)与ArrayIndexOutOfBoundsException(Java)
我只是为我的一个朋友实现了一个酷而简单的棋盘游戏。 因为他想让游戏在安卓和Windows桌面上运行,我正在安卓 Studio中用java实现安卓版本,在VS2019 C#中实现Windows桌面版本。净
我现在正试图将以下java异常移植到C#。网以下是java代码:
package eu.georgtoth.game.exceptions;
import eu.georgtoth.game.constants.BOARDCOLUMN;
import java.lang.ArrayIndexOutOfBoundsException;
import java.lang.IndexOutOfBoundsException;
/**
* BoardIndexOutOfBoundsException extends {@link ArrayIndexOutOfBoundsException}
* thrown, when column {@link BOARDCOLUMN} and row {@link Integer} are out of board bounces!
*/
public class BoardIndexOutOfBoundsException extends ArrayIndexOutOfBoundsException {
/**
* constructor with message calling super ctor {@link ArrayIndexOutOfBoundsException(String s)}
* @param message {@link String} for exception message
*/
public BoardIndexOutOfBoundsException(String message) { super(message); }
/**
* constructor with message and inner exception using {@link #initCause(Throwable throwable)}
* @param message {@link String} detailed exception message
* @param throwable {@link Throwable} for inner exception
*/
public BoardIndexOutOfBoundsException(String message, Throwable throwable) {
this(message);
super.initCause(throwable);
}
/**
* constructor with board column and row indexer, calling base ctor
* with inner exception (@link IndexOutOfBoundsException) as Throwable {@link Throwable}
* @param column board {@link BOARDCOLUMN} column indexer
* @param row board {@link Integer} row indexer
*/
public BoardIndexOutOfBoundsException(BOARDCOLUMN column, int row) {
this("board accessor out of bounce at field: " + column.getName() + row,
((IndexOutOfBoundsException)
(new Throwable("out of bounds at colunn=" + column.getValue() + ", row=" + row))));
}
}
https://docs.oracle.com/javase/9/docs/api/java/lang/ArrayIndexOutOfBoundsException.html https://docs.oracle.com/javase/9/docs/api/java/lang/IndexOutOfBoundsException.html
我有以下问题:
在C#中没有某些Whatexception的详细具体数组索引,只有IndexOutOfRangeException
IndexOutOfRangeException是一个密封的(某种框架)类,不能继承
但在中国还有另一个“出类拔萃”的例外。NET,称为ArgumentOutOfRangeException
我仍然不能准确地从语义上理解完整的层次结构。NET异常,在异常子类树中有许多相似的同级(叶节点)。 (在C#NET中过期8年后的悲剧)
有人能解释一下,什么时候应该使用IndexOutOfRangeException,什么时候ArgumentOutOfRangeException在语义上是正确的吗
在这种情况下,语义上正确的选择是什么
- 在没有派生类的情况下调用简单的IndexOutOfRangeException。(看起来不像是时髦的代码)李>
- 校准简单ArgumentOutOfRangeException李>
- 实现从ArgumentOutOfRangeException派生的框架子类李>
你好,海因里希
旁白:我知道这个问题很迂腐,但我真的不明白这里确切的形式差异。(通常在时间紧迫的工作中,我会在与同事协商后(投票或老板决定)实施一些变体,但层次结构的例外情况除外。NET与Java相比,我并不完全理解它
# 1 楼答案
IndexOutOfRangeException用于尝试访问索引超出范围的数组或集合的元素。例如,访问大小为10的数组的第11个元素
ArgumentOutOfRangeException不涉及数组。当值超出范围时使用。例如,将某人的生日设为13个月
你应该扩展哪个?Board index out bounds听起来有点像有人试图找到索引超出范围的东西。似乎无法理解的例外是一个合理的选择。但是,它扩展了SystemException,这可能不适合应用程序的异常
有什么理由不扩展异常吗?微软的文档似乎表明: https://docs.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions
他们的最佳实践文档建议尽可能使用内置的异常。IndexOutOfRangeException不适合你吗? https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions