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关键字引发异常。 。
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:
nlo, Consolas, 'Courier New', monospace; color: rgb(51, 51, 51); border-radius: 4px; margin-top: 0px; margin-bottom: 1.5em; line-height: 1.5em; word-break: break-all; word-wrap: break-word; white-space: pre-wrap; border: 1px solid rgba(0, 0, 0, 0.14902); overflow-y: auto; background-color: rgb(246, 246, 246);">
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("--------------程序结束-------------");
}
}
运行结果:
cal-align: middle; border: 0px none; text-align: center; margin: 0px auto 10px; display: block;" />