沒有try…catch,程序執行出現了異常,程序會停止執行之後的代碼;
如果有了try…catch,程序的出現的異常會被捕獲和處理,異常之後的代碼仍能繼續執行。
一、沒有try…catch
package com.exception.test;
import java.util.Scanner;
public class TryCatch {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.println("餘數爲:"+c);
System.out.println("程序繼續執行");
}
}
結果:
二、有try…catch
try…catch 包圍快捷鍵 Ctrl+Alt+T
package com.exception.test;
import java.util.Scanner;
public class TryCatch {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a,b,c;
try {
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.println("餘數爲:"+c);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("程序繼續執行");
}
}
結果: