10Java语法回顾之异常处理

Java语法回顾之异常处理


读了那么多年的书让我明白一个道理。人要稳重,不要想到啥就做啥。做一行越久即使你不会,几年之后慢慢的你也会了,加上一点努力你或许你能成为别人眼中的专家。

异常处理的格式代码

/*
 * 基本格式:
 * try{
 *      可能有问题的代码
 * }catch(异常类名 变量名){
 *      处理方案。变量名.printStackTrace();
 * }finally{
 *      释放资源。(数据库,IO)
 * }
 * 
 * finally:里面代码永远会执行。
 */

异常处理的代码测试

public class ExceptionDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入被除数:");
        int a = sc.nextInt();
        System.out.println("请输入除数:");
        int b = sc.nextInt();

        try {
            int c = a / b;
            System.out.println(c);
        } catch (ArithmeticException ae) {
            // 继续操作
            // 返回一个错误页面
            System.out.println("除数不能为0");
        }

        System.out.println("新年快乐");
    }
}

一个代码多个异常怎么解决代码测试

/*
 * 一个代码中,有多个问题,怎么解决呢?
 * A:一个个用异常处理方案解决。
 * B:针对所有问题,写一个try...catch代码。
 *      try{}catch(){}catch(){}...
 * 注意:在异常处理中,一旦try里面有问题了。就直接跳到catch里面执行。
 */
 CODE
 public class ExceptionDemo2 {
    public static void main(String[] args) {
        // method1();
        method2();
    }

    public static void method2() {
        try {
            // ArithmeticException
            int a = 10;
            // int b = 0;
            int b = 2;
            System.out.println(a / b);

            // ArrayIndexOutOfBoundsException
            int[] arr = { 1, 2, 3 };
            System.out.println(arr[3]);

            // 继续操作
            System.out.println("over");
        } catch (ArithmeticException ae) {
            System.out.println("除数不能为0");
        } catch (ArrayIndexOutOfBoundsException ae) {
            System.out.println("数组越界异常");
        }
    }
}

try……catch多个异常的顺序问题

/*
 * 注意:异常或者错误,都是以他们所在体系的父亲作为后缀。
 * XxxException
 * XxxError
 * 
 *针对多个异常,写一个try的代码,catch里面会不会有顺序问题呢?
 *如果异常是平级关系,没有顺序问题。
 *如果异常存在着子父关系,父一定要放在最后。
 */

try……catch异常JDK7新特性

/*
 * JDK7新特性:多个catch用一个catch替代。 不是说多个catch的内容,用一个Exception处理。
 * 格式:
 *      catch(异常1 | 异常2 | 异常3 ... 变量名){}
 */

Throwable异常处理方法

/*
 * Throwable中的方法:
 *      public String getMessage():返回的是异常的消息字符串。
 *      public String toString():返回异常的简单描述信息。
 *                  全路径类名 : 消息字符串
 *      public void printStackTrace():把错误信息显示在控制台。  
 */

Throwable异常处理方法代码测试

public class ExceptionDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try {
            System.out.println(a / b); // 一旦发生问题,在这里其实就产生了一个ArithmeticException对象。
                                        // 然后,拿着这个对象,去和catch里面的类型进行匹配。如果有,就赋值。
                                        // new ArithmeticException()
        } catch (ArithmeticException ae) { // ArithmeticException ae = new
                                            // ArithmeticException();
            // System.out.println("除数不能为零");
            // 通过分析,那么,ae是一个对象了
            // / by zero
            // System.out.println(ae.getMessage());

            // java.lang.ArithmeticException: / by zero
            // System.out.println(ae.toString());

            // 实际开发中,会获取到异常后,自动判断是某种异常,然后一个错误信息处理界面。
            System.out.println(ae.getMessage());
            System.out.println(ae);
            ae.printStackTrace();
        }
}

抛出异常throws

/*
 * 把异常抛出,方法调用中常见。
 * 怎么抛出呢?
 * 格式:
 *      在方法名称后面跟一个关键字:throws 异常类名
 * 
 * 异常的分类:
 *      A:Exception下非RuntimeException 编译时异常
 *      B:RuntimeException 运行时异常 
 * 
 * 异常处理:
 *      A:try...catch...finally
 *      B:throws 
 * 请问我们选择谁?
 *      如果能够处理,尽量选择A。否则选择B。
 * 
 * 运行时期异常和编译时期异常的区别?
 * A:运行时期异常 
 *      是不需要try...catch或者throws的。
 * B:编译时期异常 
 *      编译时期异常是需要进行处理的。
 * 
 */

抛出异常throws代码测试

public class ExceptionDemo {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            method();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // method();

        System.out.println("over");

        FileInputStream fis = new FileInputStream("a.txt");
        // try {
        // FileInputStream fis = new FileInputStream("a.txt");
        // } catch (FileNotFoundException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
    }

    // 告诉你,我这个方法可能有问题。请你注意。
     private static void method1() throws ArithmeticException {
     int a = 10;
     int b = 0;
     // try {
     // System.out.println(a / b);
     // } catch (ArithmeticException ae) {
     // ae.printStackTrace();
     // }
     System.out.println(a / b);
     }

    // 抛出运行时期异常
     private static void method2() throws RuntimeException {
     int a = 10;
     int b = 0;
     System.out.println(a / b);
     }

    // 抛出编译时异常
    private static void method() throws Exception {
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }
}

自定义异常类

/*
 * java虽然已经考虑到了很多种异常情况,但是,有些需求java程序是考虑不到的。比如说:我要求学生的分数不能为负数。
 * 那么,针对这种情况,我们就要编写自定义异常类进行处理。
 * 如何编写一个自定义异常类呢?
 * 就是自定义一个类,去继承Exception或者RuntimeException。
 * 开发中:一般继承自RuntimeException。
 * 我先讲Exception。
 */

自定义异常类代码测试

//1 写一个类集成Exception
public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

// 2 教师类调用这个自定义的测试类,并把异常抛出去了
public class Teacher {
    public void checkScore(int score) throws MyException {
        if (score < 0 || score > 100) {
            // System.out.println("分数错误");
            MyException my = new MyException("分数不在指定范围内");
            throw my;
        } else {
            System.out.println("分数正确");
        }
    }
}

// 3 test类中调用教师类中的方法,并捕获异常
public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生成绩:");
        int score = sc.nextInt();
        Teacher t = new Teacher();
        try {
            t.checkScore(score);
        } catch (MyException e) {
            System.out.println(e.getMessage());
            // e.printStackTrace();
        }

        // t.checkScore(score);

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值