栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java学习之RuntimeException类举例分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351105.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号