java异常库,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關鍵字引發異常。 。
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;" />
總結
以上是生活随笔為你收集整理的java异常库,java中的异常详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php ftp 创建文件夹失败,phpf
- 下一篇: java 怎么输出地址,Java中cha