java中的异常详解

java中的exception关系图如图下图所示:

Throwable是Exception(异常)和Error(错误)的超类!!

两者的区别:

Exception表示程序需要捕捉和处理的的异常;

Error表示系统级别的错误和程序无需处理的。

我们日常程序中所遇到的是Exception,Exception分为两种:

第一种是JDK标准自带的异常,当程序违反了jdk的语法规则或者非法使用内存等,程序就会抛出异常,常见的jdk异常有:

java.lang.nullpointerexception,
java.lang.classnotfoundexception
java.lang.arrayindexoutofboundsexception
java.lang.filenotfoundexception
等等。。。
第二种是程序员自己定义的异常,程序员可以创建自己的异常,并自由选择在何时用throw关键字引发异常。
所有的异常都是Thowable的子类


java中ERROR和EXCEPTION的区别

error继承父类java.lang.Error,而exception继承java.lang.Exception.EXCEPTION和ERROR都继承java.lang.Throwable,可以说,error和exception叔辈兄弟的关系

jdk中对ERROR和EXCEPTION的解释

java.lang.Error: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. ERROR用于标记严重错误。合理的应用程序不应该去try/catch这种错误!!!

java.lang.Exception: The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. 即Exception用于指示一种合理的程序想去catch的条件。即它仅仅是一种程序运行条件,而非严重错误,并且鼓励用户程序去catch它。


最后上传一个exception的demo:

package com.panther.dong.exception;

/**
 * Created by panther on 15-8-2.
 */
class MyException extends Exception {
    public void f() {
        System.out.println("this is my exception");
    }
}

public class DemoException {
    private int i = 0;
    private int j;

    DemoException(int x) throws MyException {
        f2();
        j = x / i;
    }

    public void f2() throws MyException {
        System.out.println("this is My first Exception");
        throw new MyException();
    }

    public static void main(String[] args) {
        System.out.println("-----------Exception-------------");
        try {
            new DemoException(9);
        } catch (MyException e) {
            e.f();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally is first Exception");
        }
        System.out.println("---------------------------------");
        try {
            throw new MyException();
        } catch (MyException e) {
            e.f();
        } finally {
            System.out.println("finally is second Exception");
        }
        System.out.println("--------------程序结束-------------");
    }
}

运行结果:


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值