JAVA基礎(chǔ)--如何通過異常處理錯(cuò)誤
《Thinking in Java》上對(duì)這章的講解不少,可見重要性,學(xué)習(xí)和總結(jié)一些主要的記錄下來。
一、創(chuàng)建自定義異常
package Exception;
class SimpleException extends Exception{}
public class InheritingException{
public void f() throws SimpleException {
System.out.println("Throw SimpleException from f()");
throw new SimpleException();
}
public static void main(String[] args) {
InheritingException sed = new InheritingException();
try {
sed.f();
} catch (SimpleException e) {
e.printStackTrace();
}
}
}
輸出:
Throw SimpleException from f()
Exception.SimpleException
at Exception.InheritingException.f(InheritingException.java:10)
at Exception.InheritingException.main(InheritingException.java:19)
throw與throws的區(qū)別與詳情
編譯器創(chuàng)建了默認(rèn)構(gòu)造器,它將自動(dòng)調(diào)用基類的默認(rèn)構(gòu)造器。
對(duì)異常來說,最重要的部分就是類名,其它也沒用,可以增加一個(gè)帶參的構(gòu)造方法。
比如NullPointerException:
public class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
/**
* Constructs a {@code NullPointerException} with no detail message.
*/
public NullPointerException() {
super();
}
/**
* Constructs a {@code NullPointerException} with the specified
* detail message.
*
* @param s the detail message.
*/
public NullPointerException(String s) {
super(s);
}
}
二、捕獲異常
1)try塊
如果在方法內(nèi)部拋出了異常(或者在方法內(nèi)部調(diào)用的其他方法拋出了異常),這個(gè)方法將在拋出異常的過程中結(jié)束。
要是不希望方法就此結(jié)束,可以在方法內(nèi)設(shè)置一個(gè)特殊的塊來捕獲異常。
try{
//exceptions
}
2)異常處理程序
異常處理程序緊跟在try塊之后,以關(guān)鍵字catch表示:
try{
//exceptions
} catch(Type1 id1) {
//Type1
} catch(Type2 id2) {
//Type2
}
當(dāng)異常被拋出時(shí),異常處理機(jī)制將負(fù)責(zé)搜尋參數(shù)與異常類型相匹配的第一個(gè)處理程序。然后進(jìn)入catch子句執(zhí)行,此時(shí)認(rèn)為異常得到了處理。
注意,只有匹配的catch子句才能得到執(zhí)行,這與switch語句不同。
3)棧軌跡
printStackTrace()方法所提供的信息可以通過getStackTrace()方法來直接訪問,這個(gè)方法將返回一個(gè)由棧軌跡中的元素所構(gòu)成的數(shù)組,其中每一個(gè)元素都表示
棧中的一幀。元素0是棧頂元素,并且是調(diào)用序列中的最后一個(gè)方法調(diào)用。數(shù)組中最后一個(gè)元素和棧底是調(diào)用序列中的第一個(gè)方法調(diào)用。
public class WhoCalled {
static void f() {
try {
throw new Exception();
} catch (Exception e) {
for(StackTraceElement ste : e.getStackTrace()) {
System.out.println("line: " + ste.getLineNumber() + " method: " + ste.getMethodName());
}
}
}
static void g() {f();}
static void h() {g();}
public static void main(String[] args) {f();g();h();}
}
程序輸出:
line: 5 method: f
line: 14 method: main
line: 5 method: f
line: 12 method: g
line: 14 method: main
line: 5 method: f
line: 12 method: g
line: 13 method: h
line: 14 method: main
三、Java標(biāo)準(zhǔn)異常
Throwable這個(gè)Java類被用來表示任何可以作為異常被拋出的類。
Throwable對(duì)象可分為兩種類型:
1 Error用來表示編譯時(shí)和系統(tǒng)錯(cuò)誤。
2 Exception是可以被拋出的基本類型,程序員關(guān)心的基類型通常是Exception。
四、RuntimeException
if(t == null) {
throw new NullPointerException();
}
如果對(duì)Null引用進(jìn)行調(diào)用,Java會(huì)自動(dòng)拋出NullPointerException異常,所以上述代碼是多余的,它屬于Java的標(biāo)準(zhǔn)運(yùn)行時(shí)檢測的一部分:
public class NeverCaught {
static void f() {
throw new RuntimeException();
}
static void g() {f();}
public static void main(String[] args) {
g();
}
}
輸出:
Exception in thread "main" java.lang.RuntimeException
at Exception.NeverCaught.f(NeverCaught.java:6)
at Exception.NeverCaught.g(NeverCaught.java:10)
at Exception.NeverCaught.main(NeverCaught.java:14)
從輸出可以發(fā)現(xiàn),RuntimeException是一個(gè)特例,對(duì)于這種異常類型,編譯器不需要異常說明,其輸出被報(bào)告給了System.err。
如果RuntimeException沒有被捕獲而直達(dá)main(),那么在程序退出前將調(diào)用異常的printStackTrace()方法。
*注意:
只能在代碼中忽略RuntimeException(及其子類)類型的異常,其它異常類型的處理都是由編譯器強(qiáng)制實(shí)施的。
1)常見的五種RuntimeException
NullPointerException - 空指針引用異常
ClassCastException - 類型強(qiáng)制轉(zhuǎn)換異常
IllegalArgumentException - 傳遞非法參數(shù)異常
ArithmeticException - 算術(shù)運(yùn)算異常
ArrayStoreException - 向數(shù)組中存放與聲明類型不兼容對(duì)象異常
IndexOutOfBoundsException - 下標(biāo)越界異常
NegativeArraySizeException - 創(chuàng)建一個(gè)大小為負(fù)數(shù)的數(shù)組錯(cuò)誤異常
NumberFormatException - 數(shù)字格式異常
SecurityException - 安全異常
UnsupportedOperationException - 不支持的操作異常
五、使用finally進(jìn)行清理
class ThreeException extends Exception {}
public class FinallyWorks {
static int count = 0;
public static void main(String[] args) {
while(true) {
try {
if(count++ == 0) {
throw new ThreeException();
}
System.out.println("No exception");
} catch (ThreeException e) {
System.out.println("ThreeException");
} finally {
System.out.println("In finally clause");
if(count == 2)
break;
}
}
}
}
這個(gè)程序給了我們一些思路(確實(shí)。。),如果把try塊放在循環(huán)里,就建立了一個(gè)“程序繼續(xù)執(zhí)行之前必須要到達(dá)”的條件。
還可以加入一個(gè)static類型的計(jì)數(shù)器或者別的裝置,使循環(huán)在放棄之前能夠嘗試一定的次數(shù)。這將使程序的健壯性更上一個(gè)臺(tái)階(好叼的樣子)。
1)finally用來做什么
當(dāng)要把除內(nèi)存之外的資源恢復(fù)到它們的初始狀態(tài)時(shí),就要用到finally子句。
2)在return中使用finally
因?yàn)閒inally子句總是會(huì)執(zhí)行的,所以在一個(gè)方法中,可以從多個(gè)點(diǎn)返回,并且可以保證重要的清理工作仍舊會(huì)執(zhí)行:
class ThreeException extends Exception {}
public class FinallyWorks {
static int count = 0;
public static void main(String[] args) {
while(true) {
try {
if(count++ == 0) {
throw new ThreeException();
}
System.out.println("No exception");
return;
} catch (ThreeException e) {
System.out.println("ThreeException");
} finally {
System.out.println("In finally clause");
if(count == 3)
break;
}
}
}
}
第一次循環(huán),首先執(zhí)行第7行,符合條件,拋出異常,執(zhí)行catch塊,最后執(zhí)行finally清理,不符合第16行判斷,繼續(xù)循環(huán)
第二次循環(huán),不符合第7行判斷,拋出異常,并return,但依舊執(zhí)行finally清理,不符合第16行判斷,但try塊中已經(jīng)執(zhí)行return,所以程序結(jié)束,輸出:
ThreeException
In finally clause
No exception
In finally clause
3)Java異常的缺憾:異常丟失
public class ExceptionSilencer {
public static void main(String[] args) {
try {
throw new RuntimeException();
} finally {
return;
}
}
}
以上就是JAVA基礎(chǔ)--如何通過異常處理錯(cuò)誤的詳細(xì)內(nèi)容,更多關(guān)于JAVA 通過異常處理錯(cuò)誤的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java使用Spring Batch處理大規(guī)模數(shù)據(jù)的實(shí)踐分享
在處理大規(guī)模數(shù)據(jù)的場景中,批處理是一個(gè)非常常見且必要的操作,Java中的Spring Batch是一個(gè)強(qiáng)大的框架,能夠幫助我們高效地執(zhí)行復(fù)雜的批處理任務(wù),本文將帶大家了解如何使用Spring Batch處理大規(guī)模數(shù)據(jù),并通過代碼示例展示如何實(shí)現(xiàn)高效的批處理,需要的朋友可以參考下2024-10-10
Java concurrency線程池之線程池原理(二)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了Java concurrency線程池之線程池原理第二篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
淺談java中集合的由來,以及集合和數(shù)組的區(qū)別詳解
下面小編就為大家?guī)硪黄獪\談java中集合的由來,以及集合和數(shù)組的區(qū)別詳解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10
java解析xml匯總_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了java解析xml匯總_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理的相關(guān)資料,需要的朋友可以參考下2017-07-07
Java處理InterruptedException異常的理論與實(shí)踐
在使用Java的過程中,有個(gè)情景或許很多人見過,您在編寫一個(gè)測試程序,程序需要暫停一段時(shí)間,于是調(diào)用 Thread.sleep()。但是編譯器或 IDE 報(bào)錯(cuò)說沒有處理檢查到的 InterruptedException。InterruptedException 是什么呢,為什么必須處理它?下面跟著小編一起來看看。2016-08-08
Java實(shí)現(xiàn)FTP文件與文件夾的上傳和下載
本文主要分享了Java實(shí)現(xiàn)文件上傳和下載的具體實(shí)例,分為單個(gè)文件的上傳與下載和整個(gè)文件夾的上傳與下載。具有很好的參考價(jià)值,需要的朋友一起來看下吧2016-12-12
mybatis創(chuàng)建項(xiàng)目報(bào)Invalid?bound?statement?(not?found)錯(cuò)誤解決方法
使用MyBatis能夠幫助我們將SQL語句和Java代碼分離,這篇文章主要給大家介紹了關(guān)于mybatis創(chuàng)建項(xiàng)目報(bào)Invalid?bound?statement?(not?found)錯(cuò)誤的解決方法,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05

