Java学习之RuntimeException类举例分析

Java学习之RuntimeException类举例分析

在Oracle官网上列出了RuntimeException类的直接子类
在这里插入图片描述
现分析其中的一些常见子类

1.ArithmeticException

发生情况:当发生异常算术条件时抛出。例如,整数“除以零”抛出该类的实例。

举例分析:

public class TestArithmeticException {
    public static void main(String[] args) {
        int a = 100;
        int b = 0;
        int c;
        try{
            c = a / b;
        }
        catch (ArithmeticException ae)
        {
            System.out.println(ae);
        }
    }
}
//程序输出:
//java.lang.ArithmeticException: / by zero

2.NullPointerException

发生情况:当应用程序试图在需要对象的情况下使用null时抛出。这些包括:

  • 调用null对象的实例方法。
  • 访问或修改null对象的字段。
  • null的长度视为数组。
  • 访问或修改null插槽,就像它是数组一样。
  • Throwable的值一样抛出null值。

应用程序应抛出此类实例,以指示null对象的其他非法用途。

举例分析:

public class TestNULLPointerException {
    private static int[] x;
    public  static void main(String[] args){
        try{
            System.out.println(x[0]);
        }
        catch (NullPointerException nu){
            System.out.println(nu);
        }
    }
}
//程序输出:
//java.lang.NullPointerException: Cannot load from int array because "TestNULLPointerException.x" is null

3.ClassCastException

发生情况:抛出以指示代码已尝试将对象转换为它不是实例的子类。

举例分析:

public class TestClassCastException {
    public static void main(String[] args) {
        Integer x = new Integer(0);
        String  y;
        try {
            System.out.println((String)x);
        }
        catch (ClassCastException ca){
            System.out.println(ca);
        }
    }
}
//程序输出:
//Inconvertible types; cannot cast 'java.lang.Integer' to 'java.lang.String'

4.ArrayStoreException

发生情况:抛出以指示已尝试将错误类型的对象存储到对象数组中。

举例分析:

public class TestArrayStoreException {
    public static void main(String[] args) {
        String[] x = new String[3];
        try {
            x[0] = new Integer(0);
        }
        catch (ArrayStoreException arrayStoreException){
            System.out.println(arrayStoreException);
        }
    }
}
//程序输出:
//java: 不兼容的类型: java.lang.Integer无法转换为java.lang.String

5.NegativeArraySizeException

发生情况:如果应用程序试图创建负大小的数组,则抛出。

举例分析:

public class TestArrayStoreException {
    public static void main(String[] args) {

        try {
           String[] x = new String[-1];
        }
        catch (ArrayStoreException arrayStoreException){
            System.out.println(arrayStoreException);
        }
    }
}
//程序输出:
//Exception in thread "main" java.lang.NegativeArraySizeException: -1
//at TestArrayStoreException.main(TestArrayStoreException.java:5)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值