如何在Java中抛出适当的异常

如何在Java中抛出适当的异常,java,exception,exception-handling,Java,Exception,Exception Handling,我试图在键入无效运算符(例如$,#&)时引发异常。当一个数字被零除时也是如此。尽管应用程序正在崩溃。我想知道我是否做得对 包PrefixCalc 导入java.util.Scanner public class Expressions { public static class IllegalExpressionException extends RuntimeException { public IllegalExpressionException(String m

我试图在键入无效运算符(例如$,#&)时引发异常。当一个数字被零除时也是如此。尽管应用程序正在崩溃。我想知道我是否做得对

包PrefixCalc

导入java.util.Scanner

public class Expressions {

    public static class IllegalExpressionException extends RuntimeException {

        public IllegalExpressionException(String message) {
            super("Illegal expression: " + message);
        }
    }

    private static class Calculator {

        private final boolean Calc; // ?Is this a Calc? else internal
        private final char op; // For an internal node, the operator
        private double value; // For a Calc, the value
        private Calculator left, // Left subexpression (internal node)
                right; // Right subexpression
// Bare-bones constructor

        private Calculator(boolean Calc, char op, double value) {
            this.Calc = Calc;
            this.op = op;
            this.value = value;
            this.left = null; // Empty to start
            this.right = null;
        }
// For Calc nodes, show the value; for internal, the operator.

        public @Override
        String toString()// Overrides Object.toString, must be public.
        {
            return Calc ? Double.toString(value) : Character.toString(op);
        }
    }
    Calculator root = null;

    public Expressions(Scanner input) {
        root = build(input);
    }

    /**
     * Based on a white-space delimited prefix expression, build the
     * corresponding binary expression tree.
     *
     * @param input The scanner with the expression
     * @return reference to the corresponding binary expression
     */
    private Calculator build(Scanner input) {

        boolean Calc;
        String token;
        double value;
        Calculator node;
        Calc = input.hasNextDouble();
        if (Calc) {
            try {
                value = input.nextDouble();
                node = new Calculator(Calc, '\0', value);
            } catch (IllegalExpressionException message) {
                throw new IllegalExpressionException("Illegal Expression Syntex!");
            }
        } else {
            try {
                token = input.next();
                node = new Calculator(Calc, token.charAt(0), 0.0);
                node.left = build(input);
                node.right = build(input);
            } catch (IllegalExpressionException message) {
                throw new IllegalExpressionException("Illegal Expression Syntex!");

            }

        }
        return node;


    }

    /**
     * Show the expression tree as a prefix expression.
     */
    public void showPreFix() {
        showPreFix(root);
        System.out.println();
    }
// Prefix expression is the result of a pre-order traversal

    private void showPreFix(Calculator node) {
        while (node != null) {
            System.out.print(node + " ");
            showPreFix(node.left);
            node = node.right; // Update parameter for right traversal
        }
    }

    /**
     * Show the expression tree as a parenthesized infix expression.
     *
     */
    public void showInFix() {
        showInFix(root);
        System.out.println();
    }
// Parenthesized infix requires parentheses in both the
// pre-order and post-order positions, plus the node
// itself in the in-order position.

    private void showInFix(Calculator node) {
        if (node != null) {

            if (!node.Calc) {
                System.out.print("( "); // Pre-order position
            }
            showInFix(node.left);
            System.out.print(node + " "); // In-order position
            showInFix(node.right);
            if (!node.Calc) // Post-order position
            {
                System.out.print(") ");
            }
        }
    }


    public double evaluate() {
        return root == null ? 0.0 : evaluate(root);
    }


    private double evaluate(Calculator node) throws ArithmeticException {
        double result; // Value to be returned
        if (node.Calc) // Just get the value of the Calc
        {
            result = node.value;
        } else {

            double left, right;
            char operator = node.op;
            if(operator != '-' && operator != '+' && operator != '/' && operator != '*') {
                        throw new ArithmeticException("Illegal Arthematic Syntex!" + operator);
                       // break;
                    }
// Capture the values of the left and right subexpressions
            left = evaluate(node.left);
            right = evaluate(node.right);
// Do the arithmetic, based on the operator
            switch (operator) {
                case '-':
                    result = left - right;
                    break;
                case '*':
                    result = left * right;
                    break;
                case '+':
                    result = left + right;
                    break;
                case '/':

                    result = left / right;

                    if (right == 0) {
                        throw new ArithmeticException("Division by zero!");
                    }
                    break;

                default:
                    throw new ArithmeticException("Illegal Arthematic Operation" + operator);
            }
        }
// Return either the Calc's value or the one we just calculated.
        result = Math.round(result * 100.0) / 100.0;
        return result;

    }
}
键入无效运算符时的输出为:

线程“main”java.lang.arithmetricException中出现异常:非法的Arthematic Syntex$ 在PrefixCalc.Expressions.evaluate处(Expressions.java:152) 在PrefixCalc.Expressions.evaluate处(Expressions.java:135) 位于PrefixCalc.PrefixCalc.main(PrefixCalc.java:25)
Java结果:1

从您的代码中,我看到Java运行时已经抛出异常。您必须处理它们并向用户显示相应的错误消息


然而,正确的做法是在执行表达式之前验证用户输入。这样可以避免调用、获取异常并在以后处理。验证用户输入,如果输入不正确,则向用户显示消息。

+1当验证发生在UI的单独代码层上时,异常实际上是处理输入验证的唯一好方法。即使这样,UI也必须捕获验证异常并通知用户输入有效数据。通常,捕获异常并重新显示完全相同的异常有点愚蠢。(有人怀疑您想要捕获算术异常。或者抛出IllegaExpressionException作为开始。)