Java-25,异常处理

Java异常:Java运行期出现的错误

观察错误的名字和行号最重要

package com.nyist;

public class TextEx {
    public static void main(String[] args) {
        int [] arr = {1,2,3};
        System.out.println(arr[3]);
    }
}

异常:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at com.nyist.TextEx.main(TextEx.java:6)

 

  • Java异常是Java提供的用于处理程序中错误的一种机制。
  • 所谓错误是指在程序运行的过程中发生的一些异常事件(如:除0溢出,数组下标越界,所要读取的文件不存在)
  • 设计良好的程序应该在异常发生时提供处理这些错误的方法,使得程序不会因为异常的发生而阻断或产生不可预见的结果。
  • Java程序的执行过程中如出现异常事件,可以生成一个异常类对象,该异常对象封装了异常事件的信息并将被提交给Java运行时系统,这个过程称为抛出(throw)异常。
  • 当Java运行时系统接受到异常对象时,会寻找能处理这一异常的代码并把当前异常对象交给其处理,这一过程称为捕获(catch)异常。

示例:

package com.nyist;

public class TextEx {
    public static void main(String[] args) {
        int [] arr = {1,2,3};
        try {
            System.out.println(arr[3]);
        }catch(ArrayIndexOutOfBoundsException arre) {
            System.out.println("系统出错,请联系管理员:ldw_123456@163.com");
        }
        System.out.println(arr[3]);
    }
}

运行结果:

系统出错,请联系管理员:ldw_123456@163.com
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at com.nyist.TextEx.main(TextEx.java:11)

 

 

 

 

 Error:系统错误,无法处理也无需处理

Exception:可以被处理的错误,可以被catch,

RuntimeException:运行时错误

 

 

 

 

posted @ 2020-03-10 22:47  润青  阅读(157)  评论(0编辑  收藏  举报