gpt4 book ai didi

java - Java任务中的错误处理

转载 作者:行者123 更新时间:2023-12-03 08:54:00 27 4
gpt4 key购买 nike

public class SomeClass {
int[] table;
int size;

public SomeClass(int size) {
this.size = size;
table = new int[size];
}

public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;

for (int i = 0; i < 6; i++) {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
}
}

当使用参数-2调用构造函数SomeClass时,将生成运行时错误:NegativeArraySizeException。

我正在尝试修改此代码,以便通过使用try,catch和throw使其表现更强健。构造函数应引发异常,但在使用非肯定参数调用时不执行任何操作。 main方法应捕获异常并打印警告消息,然后在循环的所有六个迭代中继续执行。
有人指出我正确的方向吗?

最佳答案

每当您得到负数并在主方法中对其进行处理时,就需要从 SomeClass 的构造函数中向抛出异常(最好是 IllegalArgumentException )。
您的代码应该看起来像;

public class SomeClass
{
int[] table;
int size;

public SomeClass(int size)
{
if ( size < 0 )
{
throw new IllegalArgumentException("Negative numbers not allowed");
}
this.size = size;
table = new int[size];
}

public static void main(String[] args)
{
int[] sizes = { 5, 3, -2, 2, 6, -4 };
SomeClass testInst;
for (int i = 0; i < 6; i++)
{
try
{
testInst = new SomeClass(sizes[i]);

System.out.println("New example size " + testInst.size);
}
catch (IllegalArgumentException e)
{
System.out.println(e.getMessage());
}
}
}
}

关于java - Java任务中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32146944/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com