目錄
一 、throws 關鍵字
在定義一個方法時可以使用 throws 關鍵字聲明,使用 throws 聲明的方法表示此方法不處理異常,而是交給方法的調用處進行處理
【throws 使用格式】
public 返回值類型 方法名稱(參數列表)throws 異常類{ }
使用 throws 關鍵字
class Math{
public int div(int i,int j) throws Exception{ //本方法不處理異常,由調用處進行處理
int temp = i / j; //此處有可能出現異常
return temp; //返回計算結果
}
}
public class ThrowsDemo01 {
public static void main(String[] args) {
Math m = new Math();
try { //因爲有throws,不管是否有異常,都必須處理
System.out.println("除法操作:" + m.div(10,2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序運行結果:
提問:那麼如果在主方法使用 throws 關鍵字呢,由誰處理異常?
class Math{ public int div(int i,int j) throws Exception{ //本方法不處理異常,由調用處進行處理 int temp = i / j; //此處有可能出現異常 return temp; //返回計算結果 } } public class ThrowsDemo01 { public static void main(String[] args) throws Exception{ Math m = new Math(); System.out.println("除法操作:" + m.div(10,2)); } }
因爲主方法是程序的起點,此時異常由JVM處理
二 、throw 關鍵字
與 throws 不同的是,可以直接使用 throw 拋出一個異常,拋出時直接拋出異常類的實例化對象
public class ThrowDemo01 {
public static void main(String[] args) {
try {
throw new Exception("自己拋出的異常!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序運行結果:
在開發中,throws 與 throw 怎麼應用呢?
三 、實例 ---- throws 與 throw 的應用
在上面的代碼中,通過 throws 聲明方法,如果產生異常則由調用處進行處理,但一旦出現異常,程序不會繼續執行方法後面的語句,而是直接跳到調用處的catch語句中
class Math{
public int div(int i,int j) throws Exception{ //本方法不處理異常,由調用處進行處理
System.out.println("------計算開始------");
int temp = i / j; //此處有可能出現異常
System.out.println("------計算結束------"); //如果產生了異常,程序將不會執行到此語句
return temp; //返回計算結果
}
}
public class ThrowsDemo01 {
public static void main(String[] args) throws Exception{
Math m = new Math();
try {
System.out.println("除法操作:" + m.div(10,0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序運行結果:
提問:如果有這樣的需求:如果產生異常就交給調用處進行處理,而方法繼續執行,該怎麼做呢?
回答:通過 try....catch....finally、throw、throws聯合使用
class Math{
public int div(int i,int j) throws Exception{ //本方法不處理異常,由調用處進行處理
System.out.println("------計算開始------");
int temp = 0;
try {
temp = i / j; //此處有可能出現異常
}catch (Exception e){
throw e; //如果產生異常,則拋給調用處
}finally {
System.out.println("------計算結束------"); //繼續執行方法的語句
}
return temp; //返回計算結果
}
}
public class ThrowsDemo02 {
public static void main(String[] args) throws Exception{
Math m = new Math();
try {
System.out.println("除法操作:" + m.div(10,0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序運行結果: