JAVA 處理常式異常,(try、catch、finally),(thorws)

來源:互聯網
上載者:User

標籤:

一、try語句:

    try{//這裡寫可能出現異常的程式}

    catch(Exception e){//這裡寫如果出現異常怎麼處理的程式}

 

二、throws語句

  文法:函數方法()  throws Exception {}

三、try語句樣本:

import java.util.Scanner;public class Index{    public static void main(String[] args){        Scanner in    =    new Scanner(System.in);        try{            System.out.println("請輸入一個數字:");            int a    =    in.nextInt();            System.out.println("請輸入一個數字:");            int b    =    in.nextInt();            int c    =    a%b;            System.out.println("餘數為:"+c);        }        catch(Exception e){            System.out.println("輸入錯誤");        }        //Exception 異常的意思        //後面的e 可以隨便寫,一遍寫e,因為這個是一個對象        System.out.println("程式繼續執行");    }}

 

四、throws語句樣本:

//throws Exception 的用法import java.util.Scanner;public class Index{    public static void main(String[] args) throws Exception    //程式中的異常處理代碼都不能處理所以反饋到這裡    {        try{            Myclass.t();    //調用靜態方法,測試異常,如果還有錯,在向上反饋,在往上反饋就是try語句,如果這個語句在無法處理,就反饋到主函數        }        catch(Exception e){            System.out.println("輸入錯誤");        }        System.out.println("程式繼續執行");    }}class Myclass{    static void t() throws Exception    //如果本方法有錯,向上反饋    {        Scanner in    =    new Scanner(System.in);        System.out.println("請輸入一個數字:");        int a    =    in.nextInt();        System.out.println("請輸入一個數字:");        int b    =    in.nextInt();        int c    =    a%b;        System.out.println("餘數為:"+c);    }}

 

五、finally

//finally 的用法import java.util.Scanner;public class Index{    public static void main(String[] args) throws Exception        {        try{            Myclass.t();        }        catch(Exception e){            System.out.println("輸入錯誤");        }        finally{            System.out.println("不管是否異常,我都會繼續執行");//finally就是代表這個意思,這個是跟try一起使用的        }    }}class Myclass{    static void t() throws Exception        {        Scanner in    =    new Scanner(System.in);        System.out.println("請輸入一個數字:");        int a    =    in.nextInt();        System.out.println("請輸入一個數字:");        int b    =    in.nextInt();        int c    =    a%b;        System.out.println("餘數為:"+c);    }}

 

JAVA 處理常式異常,(try、catch、finally),(thorws)

聯繫我們

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