1.要求兩數相乘等於100報錯。2.要求兩數相除等於2報錯
阿新 • • 發佈:2018-11-15
1.定義一個MulException類繼承Exception類,要求兩數相乘等於100報錯,在主類中定義一個方法, 在方法中丟擲此異常,在主方法觀察結果。
2.定義一個DivException類繼承RuntimeException類,要求兩數相除等於2報錯, 在主類中定義一個方法,在方法中丟擲此異常,在主方法觀察結果。
class MulException extends Exception{ public MulException(String msg){ super(msg); } } class DivException extends RuntimeException{ public DivException(String msg){ super(msg); } } public class Test{ public static void main(String[] args) throws Exception { MulTest(); DivTest(); } public static void MulTest() { try { int x = 10; int y = 10; if (x * y == 100) { throw new MulException("兩數相乘不等於100"); } } catch (Exception e) { e.printStackTrace(); } } public static void DivTest() { try { int x = 4; int y = 2; if (x / y == 2) { throw new DivException("兩數相除不等於2"); } } catch (Exception e) { e.printStackTrace(); } } }
執行結果: