標籤:
一、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)