java异常处理

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

package ersan;

public class TestException {

    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            int k;
            switch (i) {
            case 0:
                int zero = 0;
                try {
                    k = 911 / zero;
                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("数据异常");
                }
                break;
            case 1:
                int b[] = null;
                try {
                    k = b[0];
                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("空指针异常");
                }

                break;
            case 2:
                int c[] = new int[2];
                try {
                    k = c[9];
                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("数组超出长度");
                }

                break;
            case 3:
                try {    char ch = "abc".charAt(99);
                    
                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("类型转换出错");
                }
        
                break;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/dandan1224/p/5916428.html