一、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.四、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); }}
新聞熱點
疑難解答