异常初探(三)

来源:互联网 发布:算法提供者错误 编辑:程序博客网 时间:2024/05/17 03:38
package com.liujunhua.it01;/** * 对多异常的处理: * 1.声明异常时,建议声明更为具体的异常,这样处理的时候可以处理的更具体。 * 2.被调用的函数有几个异常,就对应几个catch块,不要定义多余的代码块。 *   如果多个catch块中的异常出现继承关系,父类异常放在最下面。 *    * 建立catch处理时,catch中的一定要定义具体的处理方式。不用简单的定义 * 一句 e.printStackTrace();也不要简单的定义一句输出语句 */public class Demo03 {public static void main(String[] args) {ExceptionTest exceptionTest = new ExceptionTest();try {int x = exceptionTest.div(4, 0);System.out.println("x = " + x);} catch (ArithmeticException e) {            e.printStackTrace();            System.out.println(e.getMessage());} catch (ArrayIndexOutOfBoundsException e) {            e.printStackTrace();            System.out.println(e.getMessage());}System.out.println("**********************");}}class ExceptionTest {//这里声明并抛出了多个异常int div(int a, int b) throws ArithmeticException ,ArrayIndexOutOfBoundsException{int[] arr = new int[a];System.out.println(arr[4]);return a / b;}}

0 0
原创粉丝点击