Skip to content

Commit

Permalink
1.添加了除数为0的异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
ychxx committed Jul 12, 2018
1 parent be44975 commit 77122ad
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.yc.ycutilslibrary.calculator;

import com.yc.ycutilslibrary.exception.YcCalculateException;

import java.math.BigDecimal;

/**
Expand Down Expand Up @@ -53,7 +55,7 @@ public static double multiply(double a, double b) {
* @param b 除数
* @return 两个参数的商
*/
public static double divide(double a, double b) {
public static double divide(double a, double b) throws YcCalculateException {
return divide(a, b, 3);
}

Expand All @@ -66,7 +68,10 @@ public static double divide(double a, double b) {
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double divide(double a, double b, int scale) {
public static double divide(double a, double b, int scale) throws YcCalculateException {
if (b == 0) {
throw new YcCalculateException("除数不能为0!");
}
/*
* 通过BigDecimal的divide方法进行除法时就会抛异常的,异常如下:
* java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(Unknown Source)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.yc.ycutilslibrary.exception;

import com.yc.ycutilslibrary.calculator.YcCalculator;

/**
* 计算异常
*/

public class YcCalculateException extends YcException{
public YcCalculateException(String msg) {
super(msg);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.yc.ycutilslibrary.exception;

/**
* 基础异常类
*/

public class YcException extends Exception {
private String msg = "";

public YcException() {
this("");
}

public YcException(String msg) {
this.msg = msg;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

0 comments on commit 77122ad

Please sign in to comment.