Java 異常: 編譯時間和運行時異常

來源:互聯網
上載者:User

Throwable 類是所有異常類的父類



RuntimeException 繼承自 Throwable



在 JDK 文檔裡面




中文意思如下:





之前,寫代碼的時候 throw 某個異常,

發現有些異常就是不需要 throws 語句(在方法聲明後面),而有些必須加上 throws 語句在方法聲明後面),

或者 try..catch(在方法體裡面)。


具體可以參見文章:http://bbs.csdn.net/topics/390279427

看一個小例子

接收控制台輸入的 兩個 int 類型數,然後將兩者相除。

package it.mark;import java.util.Scanner;public class OnExceptionDemo {public static void main(String[] args) {usingDivisionCalcu();}/** * 使用除法計算機計算數值. */private static void usingDivisionCalcu() {int[] input = new int[2];// 建立 Scanner 對象Scanner scan = new Scanner(System.in);// 等待使用者輸入while (scan.hasNextInt()) {for (int i = 0; i < 2; i++) {input[i] = scan.nextInt();}break;}// 從使用者輸入資料中,擷取被除數和除數int dividend = input[0];int divisor = input[1];calc4division(dividend, divisor);}/** * 除法計算. *  * @param dividend *            被除數 * @param divisor *            除數 */private static void calc4division(int dividend, int divisor) {int result = 0;result = dividend / divisor;System.out.println("計算結果是: " + result);}}


很明顯,除數為 0 是錯誤的。


修改一下 calc4division 方法

/** * 除法計算. *  * @param dividend *            被除數 * @param divisor *            除數 */private static void calc4division(int dividend, int divisor) {int result = 0;if (divisor == 0) {throw new ArithmeticException("除數是0,不符合人類計算規則!");}result = dividend / divisor;System.out.println("計算結果是: " + result);}



這裡可以看出,在方法 calc4division 裡面 throw ArithmeticException 異常,

但是編譯器並沒有要求我 throws 或者 try...catch


如果你換成 Exception 或者其子類,編譯器就會要求你了。


這裡,我們自己可以去直接捕獲

/** * 除法計算. *  * @param dividend *            被除數 * @param divisor *            除數 */private static void calc4division(int dividend, int divisor) {int result = 0;try {result = dividend / divisor;} catch (ArithmeticException ae) {System.out.println("除數是0,不符合人類計算規則!" + ae.getMessage());}System.out.println("計算結果是: " + result);}



最後提醒

如果你的代碼裡面出現關於 throw RuntimeException,那就要根據實際情況去處理了。

是捕獲還是讓他運行時報錯,由您決定!



更多關於 try catch
可以 go ---> 

http://blog.csdn.net/androidbluetooth/article/details/7868521





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.