Java處理異常2種機制關鍵字區別解析
阿新 • • 發佈:2020-01-24
這篇文章主要介紹了java處理異常2種機制關鍵字區別解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
在異常處理的過程中,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,不符合要求"); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。