设为首页 加入收藏

TOP

Java异常处理实例讲解(一)
2018-06-09 10:07:50 】 浏览:485
Tags:Java 异常 处理 实例 讲解

在Java这种纯面向对象编程语言中,有着“一切皆对象”的说法。所以,java也是通过类来描述程序出现的异常现象。在编译的时候,一些严重的错误,比如说语法错误,会被虚拟机检测出来。而异常指的是程序运行过程中,受到了一些阻碍,无法继续进行下去。这个时候就会抛出异常,从当前位置向上级一层一层地抛出。


1、先看一个简单例子:


package myException;


public class Demo_1 {


    public static void main(String[]args) {
        Test test1=new Test();
        int num = test1.div(2,0);
        System.out.println(num);
        System.out.println("over......");
    }
}


class Test
{
    public int div(int a, int b){16        return a / b;
    }
18}


如果程序在进行整除运算时,不小心除了0,会发生什么现象?



抛出了算术异常,程序立刻终止,因为最后一句“over......”也没有打印出来。


2、try catch语句


既然有了异常,我们就要对其进行处理。


package myException;


public class Demo_1 {


    public static void main(String[]args) {
        Test test1=new Test();
        try {
              int num = test1.div(2,0);
              System.out.println(num);
              System.out.println("exception......");
        }catch(ArithmeticException e) {
            e.printStackTrace();
        }
        System.out.println("over......");
    }
}


class Test
{
    public int div(int a, int b){
        return a / b;
    }
}



发现:如果没有使用try catch语句,出现问题时,后面的代码都无法执行。如果加上try catch语句,那么语句块以外的还能够继续执行,但是语句块内部的代码,从出现问题的地方开始,都不能执行。


那么普通的代码块可以屏蔽这个错误,使得代码块外面的继续执行吗,见下面代码:


package myException;


public class Demo_1 {


    public static void main(String[]args) throws ArithmeticException{
        Test test1=new Test();
        {
        int num = test1.div(2,0);
        System.out.println(num);
        System.out.println("over......");
        }
        System.out.println("happy");
       
    }
}


class Test
{
    public int div(int a, int b) {
        return a / b;
    }
}



结果是不可以,看来只有 try catch语句块可以。


3、throw和throws


package myException;


public class Demo_1 {


    public static void main(String[]args) throws ArithmeticException{
        Test test1=new Test();
        int num = test1.div(2,0);
        System.out.println(num);
        System.out.println("over......");
    }
}


class Test
{
    public int div(int a, int b) throws ArithmeticException{
        if(b == 0)
            throw new ArithmeticException();
        return a / b;
    }
}


基本的用法就是这样的,但是有几个注意点:


(1)throw方法体的内部,后面必须加切切实实new出来的对象,而throws用在方法名之后,不进入函数体,并且后面可以跟一个或多个类名(异常类),逗号隔开。


(2)如果一直向上抛出,而不catch,则会把异常抛给java处理机。


4、RuntimeException的特殊性


RuntimeException的子类有很多,比如上面的ArithmeticException,还有一些常见的比如IndexOutOfBoundsException(数组下标越界),NullPointerException(空指针异常)。为什么说它特殊呢?这种类型的异常通常都是由代码不当引起的,所以出现该异常时,希望程序停止,让维护人员进行代码的修改。所以在函数体内抛出的异常,函数名上是不需要申明的:


class Test
{
    p

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇层级目录结构的Makefile递归编译.. 下一篇PyQt5 中QDialog值传递

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目