java异常----2

2022/2/25 12:51:27

本文主要是介绍java异常----2,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

//类转换异常ClassCastException
class  job{}
class  student extends job {}
class doctor extends job{}
public class Test2 {
    public static void main(String[] args) {
        /**
         *      异常的分类 :
         *      所有的异常的根类为java.lang.Throwable,Throwable又派生出两个子类:
         *      Error和Exception
         *
         *
         *      Exception:
         *        Exception是程序本身能够处理的异常
         *        Exception类是所有异常类的父类,其子类对应了各种各样可能出现的异常时间。通常
         *        Java异常分为:
         *           1.RuntimeException  运行时异常
         *           2.CheckedException  已检查异常
         *
         */

        //运行时异常案例
//        int c=0;
//        System.out.println(1/c);
        /**
         * 显示结果:java.lang.ArithmeticException: / by zero
         *         at com.tcx.Test1.main(Test1.java:22)
         */
        //解决方案:ArithmeticException 异常
//        int c=0;
//        if (c!=0){
//            System.out.println(1/c);
//        }



        //NullPointerException 异常

//        String str=null;
//        System.out.println(str.charAt(0));
        /**
         * 显示结果为: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.charAt(int)" because "str" is null
         * 	         at com.tcx.Test2.main(Test2.java:35)
         */

        //解决方案:增加非空判断
//        String str=null;
//        if (str!=null){
//            System.out.println(str.charAt(0));
//        }

//
//       job a=new job();
//       student s=(student) a;
        /**
         * 显示结果为:Exception in thread "main" java.lang.ClassCastException: class com.tcx.job cannot be cast to class com.tcx.student (
         */
        //解决方案
        job a=new job();
        if (a instanceof student){
            student s=(student) a;
        }


    }
}



这篇关于java异常----2的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程