java中的exception关系图如图下图所示:
Throwable是Exception(异常)和Error(错误)的超类!!
两者的区别:
Exception表示程序需要捕捉和处理的的异常;
Error表示系统级别的错误和程序无需处理的。
我们日常程序中所遇到的是Exception,Exception分为两种:第一种是JDK标准自带的异常,当程序违反了jdk的语法规则或者非法使用内存等,程序就会抛出异常,常见的jdk异常有:
java.lang.nullpointerexception,java.lang.classnotfoundexceptionjava.lang.arrayindexoutofboundsexceptionjava.lang.filenotfoundexception
等等。。。
第二种是程序员自己定义的异常,程序员可以创建自己的异常,并自由选择在何时用throw关键字引发异常。
所有的异常都是Thowable的子类。
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("--------------程序结束-------------"); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/liu136313/article/details/47210207