异常的基本概念

程序在运行过程中可能会出现错误而中断正常的控制流,这就是异常现象。

异常是一种运行时错误,它是程序在运行时,由于系统检测到了不可能执行的操作而引起的。

 

不提供处理异常的代码的程序可能会在不期望终止的时候终止,甚至可能引发严重问题。

举例1:异常的概念

public class Test

{

    public int result(int x,int y){

        int r = x/y;

        return r;

    }

}

public class TestException

{

    public static void main(String[] args){

        new Test().result(3,0);

        System.out.println("Program is running here.");

    }

}

异常的概念

在Java中:

u 异常是以对象的形式表示的一个或一类程序运行时错误;

u 任何异常对象都是java.lang.Throwable类或其子类的对象;

u 系统以抛出异常对象的方式报告异常;

u 异常对象不仅封装了异常信息,还包含了异常发生时的“上、下文”信息。

异常的分类与结构树

u Throwable类是Java异常类体系中的根类,它有两个子类:一个是Error类,另一个是Exception类。

u Error类代表JVM系统内部错误,与具体程序无关。Error是程序无法处理的错误,比如OutOfMemoryError、ThreadDeath等。这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。

u Exception类是指程序代码中要处理的异常,这类异常的发生可能与程序运行时的数据有关,也可能与外界条件有关。程序中应当尽可能去处理这些异常。 

 

 

 

举例2:异常的处理

public class Test

{

    public int devide(int x,int y){

        if(y != 0){

            int result = x/y;

            return result;

        }

        else{

            return 8888;

        }        

    }

}

 

public class TestException

{

    public static void main(String[] args){

        int t = new Test().devide(3,0);

        System.out.println("结果:" + t);

    }

}

posted @ 2016-03-11 19:16  14软三张弘  阅读(197)  评论(0编辑  收藏  举报