异常

异常


  • 在Java中,所有的异常都有一个共同的祖先Throwable (可抛出)。Throwable 指定代码中可用异常传播机制通过Java 应用程序传输的任何问题的共性。
  • Throwable:有两个重要的子类: Exception (异常)和Error (错误).二者都是Java异常处理的重要子类,各自都包含大量子类。
  • Error (错误) :是程序无法处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时JVM (Java 虚拟机)出现的问题。例如,Java 虚拟机运行错误(Virtual MachineError),当JVM不再有继续执行操作所需的内存资源时,将出现OutOfMemoryError. 这些异常发生时,Java 虚拟机(VM) - 般会选择线程终止。这些错误表示故障发生于虚拟机自身、或者发生在虚拟机试图执行应用时,如Java虚拟机运行错误(Virtual Machinerror)、类定义错误(NoClassDefoundError)等。这些错误是不可查的,因为它们在应用程序的控制和处理能力之外,而且绝大多数是程序运行时不允许出现的状况。对于设计合理的应用程序来说,即使确实发生了错误,本质上也不应该试图去处理它所引起的异常状况。在Java 中,错误通过Error的子类描述。
  • Exception (异常) :是程序本身可以处理的异常。
  • Exception类有一个重要的子类RunimeException。 RuntimeException 类及其子类表示"JVM常用操作”引发的错误。例如,若试图使用空值对象引用、除数为零或数组越界,则分别引发运行时异常(NullPointerException 、ArithmeticException) 和ArrayIndexOutOfBoundException。注意:异常和错误的区别:异常能被程序本身可以处理,错误是无法处理。
一:如何抛出异常
常见异常
---------------------------------------------------------------------------------
public static void start() {
    Scanner scanner = new Scanner(System.in);
    int num1 = scanner.nextInt();
    int num2 = scanner.nextInt();
    int result = devide(num1, num2);
    System.out.println("result: " + result);
    scanner.close();
}
public static int devide(int num1, int num2) {
    return num1 / num2 ;
}
/*
2 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
 */
---------------------------------------------------------------------------------

1.手动抛出异常
---------------------------------------------------------------------------------
String str = null;
if(str == null) {
    throw new NullPointerException();
}
---------------------------------------------------------------------------------

2.程序自己抛出异常,然后捕获
---------------------------------------------------------------------------------
try {
    int a = 10;
    int b = a / 0;
    System.out.println(b);//这个值无法打印
} catch (ArithmeticException e) {
    System.out.println("ArithmeticException 异常");
    e.printStackTrace();
}

try {
    int[] array = {1, 2, 3, 4};
    System.out.println(array[4]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("数组越界");
    e.printStackTrace();
}
---------------------------------------------------------------------------------

3.try......catch......finally 捕捉多个异常
---------------------------------------------------------------------------------
public static void fun2(){
    //这里已经处理了异常,不需要再声明异常了。如果加了声明,
    // 当前函数就不处理了,调用该函数的一方进行处理。

    Scanner scan = new Scanner(System.in);
    try {
        int num1 = scan.nextInt();
        int num2 = scan.nextInt();
        int result = devide(num1, num2);
        System.out.println("result:" + result);
    } catch (ArithmeticException e) {
        System.out.println("ArithmeticException 异常");
        e.printStackTrace();
    } catch (InputMismatchException e) {//输入有误的时候
        System.out.println("InputMismatchException 异常");
        e.printStackTrace();
    } finally {
        scan.close();
    }
}
---------------------------------------------------------------------------------
二:自定义异常类进行捕捉
---------------------------------------------------------------------------------
class SimpleException extends Exception {//自定义类,继承Exception
/* public SimpleException(String name) {
     super(name); 
 }*/
}
public class TestDemo5 {
    public static void fun1() throws SimpleException {
        System.out.println("throw SimpleException");
        throw new SimpleException();//抛出异常,被catch捕获 //可以给参数
       
    public static void main(String[] args) {
        TestDemo5 test = new TestDemo5();
        try {
            test.fun1();
        }catch (SimpleException e) {
            System.out.println("SimpleException 异常被捕捉");
            e.printStackTrace();
        }
    }
}
---------------------------------------------------------------------------------

练习:
      练习1: (2) 编写一个类,在其main0方法的try块里抛出一个Exception类的对象。传递-一个字符串参数给Exception的构造器。在catch子句里捕获此异常对象,并且打印字符串参数。添加一个finally子句,打印一条信息以证明这里确实得到了执行。

      练习2: (1)定义一个对象引用并初始化为null,尝试用此引用调用方法。把这个调用放在try-catch子句里以捕获异常。

      练习3: (1) 编写能产生并能捕获ArrayIndexOutOfBoundsException异常的代码。

      练习4: (2)使用extends关键宇建立-个自定义异常类。为这个类写一个接受字符串参数的构造器,把此参数保存在对象内部的字符串引用中。写一个方法显示此字符串。写- -try-catch子句,对这个新异常进行测试。
---------------------------------------------------------------------------------
public class TestDemo6 {
    public static void main(String[] args) {
        //练习1
        try {
            throw new Exception("Exception");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("It is ending");
        }

        //练习2
        String str = null;
        try {
            int len = str.length();
        }catch (NullPointerException e) {
            e.printStackTrace();
        }

        //练习3
        try {
            int[] array = {1, 2, 3, 4};
            System.out.println(array[4]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界");
            e.printStackTrace();
        }
    }
}
三:捕获多个异常(上面有)
public static void fun2(){
    //这里已经处理了异常,不需要再声明异常了。如果加了声明,
    // 当前函数就不处理了,调用该函数的一方进行处理。

    Scanner scan = new Scanner(System.in);
    try {
        int num1 = scan.nextInt();
        int num2 = scan.nextInt();
        int result = devide(num1, num2);
        System.out.println("result:" + result);
    } catch (ArithmeticException e) {
        System.out.println("ArithmeticException 异常");
        e.printStackTrace();
    } catch (InputMismatchException e) {//输入有误的时候
        System.out.println("InputMismatchException 异常");
        e.printStackTrace();
    } finally {
        scan.close();
    }
}
                                 2018.11.15/周四
                                 by 922
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值