Java-06异常-01-常见异常

本题注意ClassCastException异常与NumberFormatException异常的区别

自己编码以产生常见异常。
main方法:

事先定义好一个大小为5的数组。
根据屏幕输入产生相应异常
提示:可以使用System.out.println(e)打印异常对象的信息,其中e为捕获到的异常对象。

输入说明

arr,代表产生访问数组产生的异常。然后输入下标,如果抛出ArrayIndexOutOfBoundsException异常则显示,如果不抛出异常则不显示。
null,产生NullPointerException
cast,尝试将String对象强制转化为Integer对象,产生ClassCastException。
num,然后输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。
其他,结束程序。

输入样例:

arr 4
null
cast
num 8
arr 7
num a
other

输出样例:

java.lang.NullPointerException
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
java.lang.ArrayIndexOutOfBoundsException: 7
java.lang.NumberFormatException: For input string: “a”

import java.util.Scanner;
public class Main {
    public static void main(String []args){
        int []a={1,2,3,4,5};
        Scanner sc = new Scanner(System.in);
        String next = sc.next();
        while (!next.equals("other")){

               if (next.equals("arr")) {
                   try {
                       a[sc.nextInt()]=2;
               } catch (ArrayIndexOutOfBoundsException e){
                       System.out.println(e);
                   }
                next= sc.next();
               }
               else if(next.equals("null")){
                   try {
                       throw new NullPointerException();
                   } catch (NullPointerException e){
                       System.out.println(e);
                   }
                   next= sc.next();
               }
               else if(next.equals("cast")){
                   try {
                       Object ss = new String("woshichaoren");//⚠️注意这里
                        Integer b = (Integer) ss;
                   } catch (ClassCastException e){
                       System.out.println(e);
                   }
                   next=sc.next();
               }
               else if(next.equals("num")){
                   try {
                       int c=Integer.parseInt(sc.next());
                   } catch (NumberFormatException e){
                       System.out.println(e);
                   }
                   next= sc.next();
               }
               else
                   break;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值