Java學習筆記----異常

來源:互聯網
上載者:User

Java學習筆記----異常

這是從別的網站盜來的圖。異常分為兩種:Error:這是程式無法處理的錯誤Exception:這是異常,又分為兩種:  處理異常的方法:拋出異常:throws 舉個例子,汽車出現故障了,汽車自己沒辦法處理,就只能交給人去處理throw出現在函數體裡面,這個算是自訂了一個自己的異常類。可以輸出自己所定義的異常。注意:這個throw也是需要throws MyException的。一開始我以為不用。所以出錯了代碼: 

package com.ehealth.exc;import java.lang.Exception;public class ExcTest {    static int question(int x,int y) throws MyException{        if(y<0){            throw new MyException("除數不能是負數");        }        return x/y;    }    static int que(int x,int y ) throws MyException{        if(x<0){            throw new MyException("第一個數字不能小於0");        }        return x+y;    }    public static void main(String[] args) {        // TODO Auto-generated method stub        int x=3;        int y=-1;        int i=-1;        int j=1;        try {            int a=que(i,j);        } catch (MyException e1) {            // TODO Auto-generated catch block            System.out.println(e1.getMessage());        }        try{            int res=question(x,y);        }catch(MyException e){            System.out.println(e.getMessage());        }catch(ArithmeticException e){            System.out.println(e.getMessage());        }catch(Exception e){            System.out.println("程式發生了其他的異常!");        }    }}class MyException extends Exception{    String message;    public MyException(String Err){        message=Err;    }    public String getMessage(){        return message;    }}

 

 

聯繫我們

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