這篇文章主要介紹了java處理異常的機制關鍵字throw和throws使用解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
在異常處理的過程中,throws和throw的區別是?
throws:是在方法上對一個方法進行聲明,而不進行處理,而是向上傳,誰調用誰處理.
throw:是在具體的拋出一個異常類型.
throws的栗子:
throws的話,就是這個方法有可能會產生異常,而我只是將它聲明出去,我自己不處理,如果有人調用的時候,可以知道,這個方法,有可能會拋出異常,我要是調用的話,我就得處理,或者接着throws.
格式是:方法名(參數)throws 異常類1,異常類2,.....
class Math{ public int div(int i,int j) throws Exception{ int t=i/j; return t; } } public class ThrowsDemo { public static void main(String args[]) throws Exception{ Math m=new Math(); System.out.println("出發操作:"+m.div(10,2)); } }
throw:在一個有異常中的方法中,可以進行捕獲,也可以進行throws
注意throws:一旦被執行,程序就會立即轉入異常處理階段,後面的語句就不再執行了,而且所在的方法不再返回有意義的值.
public class TestThrow { public static void main(String[] args) { try { //調用帶throws聲明的方法,必須顯式捕獲該異常 //否則,必須在main方法中再次聲明拋出 throwChecked(-3); } catch (Exception e) { System.out.println(e.getMessage()); } //調用拋出Runtime異常的方法既可以顯式捕獲該異常, //也可不理會該異常 throwRuntime(3); } public static void throwChecked(int a)throws Exception { if (a > 0) { //自行拋出Exception異常 //該代碼必須處於try塊裏,或處於帶throws聲明的方法中 throw new Exception("a的值大於0,不符合要求"); } } public static void throwRuntime(int a) { if (a > 0) { //自行拋出RuntimeException異常,既可以顯式捕獲該異常 //也可完全不理會該異常,把該異常交給該方法調用者處理 throw new RuntimeException("a的值大於0,不符合要求"); } } }
文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值