學會try/catch/throw的用法。做出一個計算器除法功能,除以0時程序必須給出提示。
自己的理解:
try:指這一段會出現報錯,在try{}中出現錯誤可進行調用
catch:接收出錯異常,最後可顯示出編輯的異常顯示
throw:拋出異常,一般出錯系統會拋出異常,throw可以拋出自定義異常
做一個計算器除法,除以0時給出提示(throw不知道該怎麼寫進去)
package Q7;
import java.util.Scanner;
public classQ7 {
public static void main (String[] args){
System.out.println("請輸除數");
Scannerscanner=newScanner(System.in);
try{ //try中的所有異常進行調用
int a =scanner.nextInt();
System.out.println("請輸除數");
int b =scanner.nextInt();
int d=0;
d = a/b;
System.out.println("結果="+d);
}
catch (ArithmeticException e )//接收異常處理
{
System.out.println("被除數不能爲0");//異常提示
}
catch (Exception e) {//接收異常處理
System.out.println("輸入錯誤");//異常提示
}
}
}