简体   繁体   中英

Java : How to check if a method throws a exception and terminate when it does?


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();
    }
}

The main method takes the input (2 numbers and an operator('+' or '-' or '/' or '*' only) and passes it to the calculate method. The calculate method should check for an exception and if there is no exception, return the calculated value to the main function ie v1+v2 or v1-v2; Else if an exception exists then it should print the error statement and the value that is returned from the calculate method to the main method should be 0.0(Not printed).

You can try in below way and should work fine. You can even overide Exception constructor to pass error message from exception and print e.getMessage() at place where exception is caught. I have just given you working code with simple message print.

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();
    }
}

UPD: I made mistake you should use

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

instead

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

You can use Exception(String message) constructor for your excaptions. Also I think you should use Enum for indicate operators

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);
    }
}
}

You can do something like

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, '-'));
    }
}

I have written enough comments in the code so that you can understand it easily.

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM