java:如何检查方法是否抛出异常并在抛出异常时终止?

qcbq4gxm  于 2021-07-12  发布在  Java
关注(0)|答案(3)|浏览(466)
class Exceptions {
    public String checkExceptions(double n1, double n2, char op) throws DivideByZeroException, MultiplyByZeroException{
        try {
            if(op == '/' && n2==0) {
                throw new DivideByZeroException();
            }
            else if(op=='*' && (n1==0 || n2==0)) {
                throw new MultiplyByZeroException();
            }
            else {
                return "No exception found";
            }
        } 
        catch (DivideByZeroException ex) {
            return "Division by zero results in infinity";
        }
        catch(MultiplyByZeroException ex) {
            return "Multiplying by zero";
        }
        catch(Exception ex) {
            return op+" not a valid operator";
        }
    }

    public double calculate(double v1, double v2, char op) throws Exception{  //Error: This method must return a result of type double
        try{
            checkExceptions(v1, v2, op);   //This might be wrong place to put the method. Don't know how to check if this method throws an exception or not.
            if(op=='+') {
                return v1+v2;
            }
            else if(op=='-') {
                return v1-v2;
            }
            else{
                return 0.0;
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
        }

    }
}

class DivideByZeroException extends Exception{
    DivideByZeroException(){
        super();
    }
}

class MultiplyByZeroException extends Exception{
    MultiplyByZeroException(){
        super();
    }
}

main方法接受输入(2个数字和一个运算符(“+”或“-”或“/”或“*”),并将其传递给calculate方法。计算方法应检查是否有异常,如果没有异常,则将计算值返回到主函数v1+v2或v1-v2;否则,如果存在异常,则应打印错误语句,并且从calculate方法返回到main方法的值应为0.0(未打印)。

q7solyqu

q7solyqu1#

你可以在下面的方式尝试,应该工作得很好。您甚至可以覆盖异常构造函数,从异常传递错误消息,并在捕获异常的位置打印e.getmessage()。我刚刚给你简单的消息打印工作代码。

class Exceptions {
    public void checkExceptions(double n1, double n2, char op) throws DivideByZeroException, MultiplyByZeroException {
        if (op == '/' && n2 == 0) {
            throw new DivideByZeroException();
        } else if (op == '*' && (n1 == 0 || n2 == 0)) {
            throw new MultiplyByZeroException();
        }
    }

    public double calculate(double v1, double v2, char op) throws Exception {  
        double result = 0.0;
        try {
            checkExceptions(v1, v2, op); 
            switch(op){
                case '+' : result = v1 + v2;
                          break;
                case '-' : result = v1 - v2;
                    break;
                case '/' : result = v1 / v2;
                    break;
                case '*' : result = v1 * v2;
                    break;
            }
        } catch (DivideByZeroException ex) {
            System.out.println("Division by zero results in infinity");
        } catch (MultiplyByZeroException ex) {
            System.out.println("Multiplying by zero");
        } catch (Exception ex) {
            System.out.println(op + " not a valid operator");
        }
        return result;
    }
}

class DivideByZeroException extends Exception {
    DivideByZeroException() {
        super();
    }
}

class MultiplyByZeroException extends Exception {
    MultiplyByZeroException() {
        super();
    }
}
chhqkbe1

chhqkbe12#

你可以这样做

class Exceptions {
    public String checkExceptions(double n1, double n2, char op) throws DivideByZeroException, MultiplyByZeroException {
        if (op == '/' && n2 == 0) {
            throw new DivideByZeroException("Division by zero results in infinity");
        } else if (op == '*' && (n1 == 0 || n2 == 0)) {
            throw new MultiplyByZeroException("Multiplying by zero");
        } else {
            return "No exception found";
        }
    }

    public double calculate(double v1, double v2, char op) {
        double result = 0;
        try {
            System.out.println(checkExceptions(v1, v2, op));// Print the message
            if (op == '+') {
                result = v1 + v2;
            } else if (op == '-') {
                result = v1 - v2;
            } else if (op == '/') {
                result = v1 / v2;
            } else if (op == '*') {
                result = v1 * v2;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return result;// Return result
    }
}

class DivideByZeroException extends Exception {
    DivideByZeroException(String message) {// Parametrise it
        super(message);// Pass the parameter to the constructor of super class
    }
}

class MultiplyByZeroException extends Exception {
    MultiplyByZeroException(String message) {// Parametrise it
        super(message);// Pass the parameter to the constructor of super class
    }
}

public class Main {
    public static void main(String[] args) {
        Exceptions e = new Exceptions();
        System.out.println(e.calculate(10, 0, '/'));
        System.out.println(e.calculate(10, 5, '/'));
        System.out.println(e.calculate(10, 5, '*'));
        System.out.println(e.calculate(10, 0, '*'));
        System.out.println(e.calculate(10, 5, '+'));
        System.out.println(e.calculate(10, 5, '-'));
    }
}

我已经在代码中写了足够的注解,这样您就可以很容易地理解它。
输出:

Division by zero results in infinity
0.0
No exception found
2.0
No exception found
50.0
Multiplying by zero
0.0
No exception found
15.0
No exception found
5.0
anhgbhbe

anhgbhbe3#

upd:我犯了一个你应该用的错误

Arrays.asList(Arrays.stream(Operators.values()).map(en -> en.op)).contains(op)

相反

Arrays.asList(Operators.values()).contains(op)

你可以用 Exception(String message) 为你的例外建造师。另外,我认为应该使用enum来表示运算符

class Exceptions {

    public enum Operators {
        PLUS('+'),
        SUB('-'),
        DIV('/'),
        MUL('*');

        public final char op;

        Operators(char op) {
           this.op = op;
        } 
    }

    public void checkExceptions(double n1, double n2, char op) throws Exception {
        if (op == Operators.DIV.op && n2 == 0) {
            throw new DivideByZeroException("Division by zero!");
        } else if (op == Operators.MUL.op && (n1 == 0 || n2 == 0)) {
            throw new MultiplyByZeroException("Multiplying by zero!");
        } else if(Arrays.asList(Arrays.stream(Operators.values()).map(en -> en.op)).contains(op)) {
            throw new Exception(op + " not a valid operator!");
        }
    }

    public double calculate(double v1, double v2, char op) {
        try {
            checkExceptions(v1, v2, op);
            if (op == Operators.PLUS.op) {
                return v1 + v2;
            } else if (op == Operators.SUB.op) {
                return v1 - v2;
            } else if (op == Operators.MUL.op){
                return v1 * v2;
            } else if(op == Operators.DIV.op) {
                return v1 / v2;
            } else {
                return 0.0;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return 0.0;
        }
}

class DivideByZeroException extends Exception {
    DivideByZeroException(String message) {
        super(message);
    }
}

class MultiplyByZeroException extends Exception {
    MultiplyByZeroException(String message) {
        super(message);
    }
}
}

相关问题