java異常throw 與 throws關鍵字有什麼區別?

來源:互聯網
上載者:User

 

1.throws 用於拋出方法層次的異常,
並且直接由些方法調用異常處理類來處理該異常,
所以它常用在方法的後面。比如
public static void main(String[] args) throws SQLException

2.throw 用於方法塊裡面的代碼,比throws的層次要低,比如try...catch ....語句塊,表示它拋出異常,
但它不會處理它,
而是由方法塊的throws Exception來調用異常處理類來處理。

throw用在程式中,明確表示這裡拋出一個異常。   
throws用在方法聲明的地方,表示這個方法可能會拋出某異常。

throw是拋出一個具體的異常類,產生一個異常。
throws則是在方法名後標出該方法會產生何種異常需要方法的使用者捕獲並處理。

1、throws關鍵字通常被應用在聲明方法時,用來指定可能拋出的異常。多個異常可以使用逗號隔開。當在主函數中調用該方法時,如果發生異常,就會將異常拋給指定異常對象。如下面例子所示:public class Shoot {   建立類static void pop() throws NegativeArraySizeException {//定義方法並拋出NegativeArraySizeException異常int [] arr = new int[-3];//建立數組}public static void main(String[] args) {//主方法try { pop(); //調用pop()方法} catch (NegativeArraySizeException e) {System.out.println("pop()方法拋出的異常");//輸出異常資訊}}}2、throw關鍵字通常用在方法體中,並且拋出一個異常對象。程式在執行到throw語句時立即停止,它後面的語句都不執行。通過throw拋出異常後,如果想在上一級代碼中來捕獲並處理異常,則需要在拋出異常的方法中使用throws關鍵字在方法聲明中指明要跑出的異常;如果要捕捉throw拋出的異常,則必須使用try—catch語句。舉例如下:class MyException extends Exception { //建立自訂異常類 String message; //定義String類型變數 public MyException(String ErrorMessagr) {  //父類方法       message = ErrorMessagr; } public String getMessage(){   //覆蓋getMessage()方法  return message; }}public class Captor { //建立類static int quotient(int x,int y) throws MyException{//定義方法拋出異常if(y < 0){  //判斷參數是否小於0         throw new MyException("除數不能是負數");//異常資訊 } return x/y;//傳回值 }public static void main(String args[]){ //主方法 try{ //try語句包含可能發生異常的語句                int result = quotient(3,-1);//調用方法quotient()    }catch (MyException e) { //處理自訂異常  System.out.println(e.getMessage()); //輸出異常資訊  }    catch (ArithmeticException e) {                   //處理ArithmeticException異常  System.out.println("除數不能為0");//輸出提示資訊  }   catch (Exception e) { //處理其他異常  System.out.println("程式發生了其他的異常");                  //輸出提示資訊  } }} 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.