自定义异常类NegativeException
生活随笔
收集整理的這篇文章主要介紹了
自定义异常类NegativeException
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
輸入兩個(gè)數(shù),輸出兩個(gè)數(shù)的商,自定義異常類NegativeException和ZeroException用于檢測(cè)輸入的除數(shù)為負(fù)數(shù)和零時(shí),拋出異常。
package hello;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);System.out.println("Please input first number: ");double fenzi = in.nextDouble();System.out.println("Please input second number: ");double fenmu = in.nextDouble();Chufa s = new Chufa(fenzi, fenmu);try {s.ff();} catch (ZeroException e) {e.warn(fenmu);} catch (NegativeException m) {m.warn(fenmu);} finally {System.out.println("finally!");}}}class NegativeException extends Exception {public void warn(double mu) {System.out.println("The divisor, " + (int)mu + ", could not be negative!");} }class ZeroException extends Exception {public void warn(double mu) {System.out.println("The divisor, " +(int) mu + ",could not be zero!");} }class Chufa {double fenzi, fenmu;Chufa(double zi, double mu) {fenzi = zi;fenmu = mu;}public void ff() throws NegativeException, ZeroException {if (fenmu > 0) {System.out.println("Divisor is : " + fenzi / fenmu);} else if (fenmu == 0) {throw new ZeroException();} else {throw new NegativeException();}}}總結(jié)
以上是生活随笔為你收集整理的自定义异常类NegativeException的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 避免摄像机穿透地形模型
- 下一篇: 怎样存储layui模板引擎后台返回的数据