throw與throws用法
阿新 • • 發佈:2019-02-20
rgs alt mismatch http lse n) fin 分享圖片 int
throw與throws用法
給年齡賦值如果小於1或者大於100則拋出異常
package com.異常; /** * 拋出異常 */ import java.util.InputMismatchException; import java.util.Scanner; /** * 人的年齡 */ public class Test2 { //年齡 private int age; //set年齡 public void SetAge(int age)throws Exception { //聲明異常 if(age>0&&age<=100) { this.age=age; }else { throw new Exception("請輸入1到100之間的數值!"); //拋出異常 } } //get年齡 public int GetAge() { return age; } }
/** * 測試類 * @author Administrator * */ class TestMain{ public static voidmain(String[] args) throws Throwable { Scanner sc=new Scanner(System.in); Test2 t=new Test2(); System.out.println("請輸入年齡"); try { t.SetAge(sc.nextInt()); //給年齡賦值 }catch(InputMismatchException e) { //捕捉不是數字的異常System.err.println("您輸入的不是數字"); }finally { //輸出最終結果 System.out.println("您的年齡是:"+t.GetAge()); } } }
運行
正常情況
輸入小於1或者大於100的情況
輸入不是數字的情況
throw與throws用法