Java 异常处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 异常处理相关的知识,希望对你有一定的参考价值。

建立exception包,编写TestException.java程序,主方法中有以下代码,确定其中可能出现的异常,进行捕获处理。

 

public static void main(String[] args) {


        for(int i=0;i<4;i++){
            int  k;
            
            switch(i){
                case 0:
        try{            
        int zero=0;
        k=911/zero;}
        catch (ArithmeticException e) {
            System.out.println("输入有误");
        }
        break;
                case 1:
        try{            
        int  b[]=null;
        k = b[0];}
        catch (NullPointerException e) {
            System.out.println("空指针异常");
        }
        break;
                case 2:
        try{            
        int c[]=new int[2];

        k=c[9];}
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("索引超出异常");
        }
        break;
                case 3:
        try{            
        char  ch="abc".charAt(99);}
        catch (Exception e) {
            System.out.println("收取字符超出");
            e.printStackTrace();
        }

        break;
            }
        }


    }

}

技术分享

以上是关于Java 异常处理的主要内容,如果未能解决你的问题,请参考以下文章

使用片段中的处理程序时出现非法状态异常

异常和TCP通讯

java.util.MissingResourceException: Can't find bundle for base name init, locale zh_CN问题的处理(代码片段

java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.database.sqlite异常(代码片段

java异常 throw和try-catch的关系

PCL异常处理:pcl 1.8.13rdpartyoostincludeoost-1_64oost ypeofmsvc ypeof_impl.hpp(125): error(代码片段