题目描述:
自行编码产生常见异常。
main方法
- 事先定义好一个大小为5的数组。
- 根据屏幕输入产生相应异常。
**提示:**可以使用System.out.println(e)打印异常对象的信息,其中e为捕获到的异常对象。
输入说明:
arr代表产生访问数组是产生的异常。然后输入下标,如果抛出ArrayIndexOutOfBoundsException异常则显示,如果不抛出异常则不显示。null,产生NullPointerExceptioncast,尝试将String对象强制转化为Integer对象,产生ClassCastException。num,然后输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。- 其他,结束程序。
输入样例:
arr 4
null
cast
num 8
arr 7
num a
other
输出样例:
java.lang.NullPointerException java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 java.lang.NumberFormatException: For input string: "a"
答案:
import java.util.*;
class Main{
public static void main(String[] args){
int[] arr = new int[5];
Scanner sc = new Scanner(System.in);
while(true) {
String choice = sc.next();
try {
if ("arr".equals(choice)) {
int index = sc.nextInt();
int num = arr[index];
} else if("null".equals(choice)){
throw new NullPointerException();
}else if("cast".equals(choice)) {
Object obj = new String("dsf");
Integer num = (Integer)obj;
}else if("num".equals(choice)){
String str = sc.next();
Integer num = Integer.parseInt(str);
}else{
break;
}
}catch (Exception e){
System.out.println(e);
}
}
}
}
解析:
这题有点意思,自己故意写报错还从来没试过( - v -)
该程序演示了如何在Java中生成并处理常见的运行时异常,如NullPointerException、ClassCastException、ArrayIndexOutOfBoundsException和NumberFormatException。用户输入指令来触发特定异常,程序捕获异常并打印相关信息。



3664

被折叠的 条评论
为什么被折叠?



