什麼是異常
異常是程序中的一些錯誤,但並不是所有的錯誤都是異常,並且錯誤有時是可以避免的。在Java中所有的異常都以類和對象的形式存在,除了Java中提供的各種異常類外,用戶也可以根據自己的需要自己的異常類。
異常處理格式
try{
//有可能出現異常的語句
}catch(異常類 異常對象){
//編寫異常處理的語句
}【catch(異常類 異常對象){
//編寫異常處理的語句
}catch(異常類 異常對象){
//編寫異常處理的語句
}】
【finally{
//一定會運行到的程序代碼
}】
如果在try中產生了異常,則程序會自動跳轉到catch語句中找到匹配的異常類型進行相應的處理。但不管程序是否會產生異常,肯定會執行到finally語句,finally語句作爲異常的統一出口,該語句是可以省略的。如果省略finally()塊語句,則在catch()塊語句執行後程序會跳到try-catch塊語句之後的語句執行。
Java的異常處理機制
按照面向對象的方式進行異常處理,處理步驟爲:
(1)一旦產生異常,則會產生異常類的實例化對象;
(2)在try語句中對此異常對象進行捕捉;
(3)產生的異常對象與catch語句中的各個異常類型進行匹配,如果匹配成功,則執行catch語句中的代碼。
package throws關鍵字;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
int j = 0;
System.out.println("************計算開始************");
try {
String str1 = args[0];
String str2 = args[1];
i = Integer.parseInt(str1);
j = Integer.parseInt(str2);
int temp = i / j;
System.out.println("兩個數相除的結果爲:" + temp);
System.out.println("-------------------------------------");
}catch(ArithmeticException e) {
System.out.println("算數異常:" + e);
}catch(NumberFormatException e) {
System.out.println("數字轉換異常:" + e);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("其他異常:" + e);
}
System.out.println("****************計算結束***************");
}
}
在Java中所有捕獲範圍小的異常必須放在捕獲範圍大的異常之前,否則程序在編譯時就會出現錯誤。
在整個Java的異常結構中,有兩個最常見的類,分別爲Exception和Error,這兩個類全都是Throwable的子類。
Exception:一般表示程序中出現的問題,可以直接使用try-catch處理,其子類有算數異常(ArithmeticException)和數字化格式異常(NumberFormatException)等;
Error:一般指的是JVM錯誤,程序中無法處理;
throws與throw關鍵字
在自定義的類方法中使用throws關鍵字時,自定義類可以不做異常處理,但主方法調用時必須使用try–catch語句;在主方法處使用throws關鍵字時,可以不再使用try–catch塊進行異常的捕獲與處理。
package throws關鍵字;
class Math{
public int div(int i,int j)throws Exception{
int temp = i / j;
return temp;
}
}
public class Test {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Math m = new Math();
try {
System.out.println("除法操作:" + m.div(10, 2));
}catch(Exception e) {
e.printStackTrace();
}
}
}
在主方法處使用throws關鍵字
package throws關鍵字;
class Math{
public int div(int i,int j)throws Exception{
int temp = i / j;
return temp;
}
}
public class Test {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Math m = new Math();
System.out.println("除法操作:" + m.div(10, 2));
}
}
主方法爲一切的起點,所有的操作是由主方法開始的。如在主方法中使用throws關鍵字,則程序出現問題後肯定交給JVM進行處理,將導致程序中斷,所以最好不要在主方法中使用throws關鍵字。