運(yùn)行時(shí)異常
- 例如數(shù)組越界,繼承與RuntimeException,在編譯期間不是必須要捕獲的異常.
public static void main(String[] args) {
Object[] arr = {1,2,3};
try {
Object obj = arr[10];//try中的異常會(huì)終止異常之后的代碼
System.out.println("錯(cuò)誤之后"); //錯(cuò)誤之后不執(zhí)行這句
} catch (Exception e) {//捕獲到異常之后執(zhí)行
//處理錯(cuò)誤
//e.printStackTrace();
System.out.println("catch塊");
}
System.out.println("1");
}
public static void main(String[] args) {
Object[] arr = {null,null,1};
//Object value = arr[10];//數(shù)組越界
try {
// Object obj = arr[10];
// arr[1].equals(1);
//其他異常
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("數(shù)組越界");
}catch (NullPointerException e) {
System.out.println("空指針異常");
}catch (RuntimeException e) {
System.out.println("其他異常");
}
System.out.println("1");
}
public static void main(String[] args) {
add();
try {
} catch (Exception e) {
}finally{//不管有沒有異常都執(zhí)行
//關(guān)閉文件
}
}
static int add(){
try {
int a = 1;
System.out.println(a);
return a;
} catch (Exception e) {
}finally{
System.out.println("finally");
}
return 1;
}
- 上面是try....catch 還有 try ....catch..catch try...catch...finally
- 必須在try之后添加catch或finally塊.try塊后可同時(shí)接catch和finally塊,但至少有一個(gè)塊.
- 必須遵循塊順序:若代碼同時(shí)使用catch和finally塊,則必須將catch塊放try塊之后.
- finally是一定會(huì)執(zhí)行的.
- throw拋出異常的兩種情況 1.拋出異常給調(diào)用者處理 2.在catch塊中捕獲到的異常不想處理,拋給調(diào)用者處理.
- throws 1.拋出異常給調(diào)用者處理 2.當(dāng)函數(shù)中拋出非運(yùn)行時(shí)異常,需要throws聲明一下.
非運(yùn)行時(shí)異常
- 例如io異常,數(shù)據(jù)庫異常,在程序編譯階段一定要使用try...catch捕獲.
- 非運(yùn)行異常是RuntimeException以外的異常,類型上都屬于Exception類及其子類,如IOException SQLException等以及用戶自定義的Exception異常, 對(duì)于這種異常,java編譯器強(qiáng)制要求我們必須對(duì)出現(xiàn)的這些異常進(jìn)行catch處理,否則程序就不能編譯通過.所以 面對(duì)這種異常不管我們是否愿意,只能自己去寫一堆catch塊處理可能的異常.
public static void main(String[] args) throws Exception{
//創(chuàng)建一個(gè)文件讀取對(duì)象
FileReader reader = new FileReader("文件的名字");//必須捕獲 非運(yùn)行時(shí)異常
// try {
// FileReader reader = new FileReader("文件的名字");//必須捕獲 非運(yùn)行時(shí)異常
// } catch (Exception e) {
//
// }
}
//當(dāng)函數(shù)中拋出非運(yùn)行時(shí)異常 需要throws聲明一下.如果拋出多個(gè) 用,隔開寫 或者直接拋出一個(gè)共同父類
void fileNotFound()throws FileNotFoundException{
int a =10;
System.out.print(a);
throw new ArrayIndexOutOfBoundsException();//無錯(cuò)
//throw new FileNotFoundException;//有錯(cuò)
}
錯(cuò)誤和異常的不同
異常:可以捕獲的.
錯(cuò)誤:一般是不可處理的 例如 虛擬機(jī)掛了.
throws和throw的不同
- throw是語句拋出一個(gè)異常
- 語法 throw(異常對(duì)象); throw e;(自己不處理 拋給調(diào)用這調(diào)用)
- throws是方法可能拋出異常的聲明(用在聲明方法時(shí),表示該方法可能要拋出異常)
- 語法:[(修飾符)(返回類型)(方法名)([參數(shù)列表])(throws(異常類型)){.......}
throws出現(xiàn)在方法函數(shù)頭,而throw出現(xiàn)在函數(shù)體中.