arrays - 使用 try、catch 和 throw 避免负数组大小异常
问题描述
以下 Java 代码:
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);
}
}
}
SomeClass 的前两个实例的大小为 5 和 3,将毫无问题地创建。但是,当使用参数 -2 调用构造函数 SomeClass 时,会生成运行时错误:NegativeArraySizeException。
如何修改上述代码,使其通过使用 try、catch 和 throw 表现得更加稳健。main 方法应捕获此异常并打印警告消息,然后继续执行循环。
我是一个java新手,所以会很感激任何帮助。
谢谢
解决方案
使类构造函数抛出错误并在主类中捕获它,如下所示:
public class SomeClass {
int[] table;
int size;
public SomeClass(int size) throws NegativeArraySizeException{
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 (NegativeArraySizeException err) {
System.out.println(err.toString());
}
}
}
}
输出将是
推荐阅读
- go - 如何为枚举类型分配默认值
- debugging - 是否可以同时使用 gdb 和嵌套的 qemu 虚拟机来调试 linux 用户空间程序和主机管理程序?
- c# - 复制或移动替换文件和更新版本共享点 CSOM
- html - cgraph库生成带有html标签属性的点文件?
- elasticsearch - 如何防止新索引的分片仅在 Elasticsearch 中的几个节点上分配?
- javascript - 如何在javascript手风琴中禁用自动滚动
- azure-logic-apps - 具有 Outlook 连接器的逻辑应用程序中的自定义标头
- composer-php - 找不到命令:作曲家
- javascript - PerformanceNavigation 的替代 Javascript 方法(跨浏览器兼容)
- sql - oracle数据库中的join表