異常處理
Exception
當(dāng)程序出現(xiàn)異常情況,有沒有處理似扔,那么程序直接終止運(yùn)行 (崩潰)
使用try-catch捕獲異常
try {
//具體的代碼塊 會(huì)捕獲這個(gè)代碼塊的異常
//當(dāng)代碼塊里面出現(xiàn)異常,后面的代碼不會(huì)執(zhí)行
//不要讓try包裹太多內(nèi)容
} catch (IndexOutOfBoundsException e) {
//使用catch來捕獲具體的一個(gè)異常
}
拋出異常時(shí),盡量不要有太多的嵌套(否則代碼結(jié)構(gòu)和閱讀性差)
不得不嵌套時(shí)盯桦,不要大于兩層
try{
具體代碼塊
}catch(){
捕獲的某種異常
}finally{
釋放資源
注意:Java只會(huì)釋放在堆或棧上的資源,不會(huì)釋放外部資源
1.需要釋放文件渤刃、網(wǎng)絡(luò)和數(shù)據(jù)庫資源
2.有些代碼不管有沒有出現(xiàn)異常都需要被執(zhí)行
}
注意當(dāng)有多個(gè)catch時(shí)拥峦,有捕獲的順序,按照子類到父類的順序catch
如果父類的異常在前面卖子,就會(huì)攔截子類的catch
如果不關(guān)心具體是什么異常略号,只是想處理一下異常,可以使用異常的父類來捕獲
catch(Exception e)
使用throw拋出異常
當(dāng)某個(gè)方法完成某個(gè)功能,當(dāng)執(zhí)行時(shí)可能出現(xiàn)異常玄柠,這種異常需要調(diào)用者自己決定該如何處理突梦,就使用throws拋出異常
自定義異常
MyClass.java
class Test{
public void download() throws IOException{
FileReader fr = null;
fr = new FileReader(s: "文件路徑");
fr.read();
ArrayList<String> list = new ArrayList<>();
//list.get(20);
String str = null;
str = (String) new Object();
}
//jack
//12jack
public void login(String name, String pwd) throws LoginException{
if (name.startsWith("1")){
//自己定義一個(gè)異常
throw new LoginException("用戶名不能以1開頭");
}
}
}
class LoginException extends Exception{
public LoginException() {
}
public LoginException(String s) {
super(s);
}
}
public class MyClass {
public static void main(String[] agrs){
Test t = new Test();
try {
t.download();
} catch {
e.printStackTrace();
}
}
public void test(){
//FileNotFoundException
// FileReader fr = new FlieReader(s: "");
//IndexOutOfBoundsException
// ArrayList<String> list = new ArrayList<>();
// list.get(2);
//NullPointerException
// String name = null;
// name.length();
//NullPointerException的捕獲
// String name = null;
// try {
// name.length();
// } catch (NullPointerException e) {
// System.out.println(e.getMessage());
// e.printStackTrace();
// }
//ClassCastExcetion
// String name = null;
// Object obj = new Object();
// name = (String) obj;
}
}