Java 中的自定义异常尝试抛出捕获

Dar*_*loc 0 java exception

当变量 d1 和 d2 不是正确的数据类型时,我总是收到默认的 NumberFormatException 消息。

当使用 throw 语句条件捕获这些异常时,我想打印我的自定义异常消息。

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a numeric value: ");
    String input1 = sc.nextLine();
    Double d1 = Double.parseDouble(input1);
    System.out.print("Enter a numeric value: ");
    String input2 = sc.nextLine();
    Double d2 = Double.parseDouble(input2);
    System.out.print("Choose an operation (+ - * /): ");
    String input3 = sc.nextLine();
    try {
        if (!(d1 instanceof Double)) {
            throw (new Exception("Number formatting exception caused by: "+d1));
        }
        if (!(d2 instanceof Double)) {
            throw (new NumberFormatException("Number formatting exception caused by: "+d2));
        }
        switch (input3) {
            case "+":
                Double result = d1 + d2;
                System.out.println("The answer is " + result);
                break;
            case "-":
                Double result1 = d1 - d2;
                System.out.println("The answer is " + result1);
                break;
            case "*":
                Double result2 = d1 * d2;
                System.out.println("The answer is " + result2);
                break; 
            case "/":
                Double result3 = d1 / d2;
                System.out.println("The answer is " + result3);
                break;
            default:
                System.out.println("Unrecognized Operation!");
                break;
        }
    }
    catch (Exception e){ 
        System.out.println(e.getMessage());
    }

}
Run Code Online (Sandbox Code Playgroud)

}

这是当输入的值格式不正确时打印的消息示例。

输入一个数值:线程“main”中的 $ Exception java.lang.NumberFormatException:对于输入字符串:“$” at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054) at java.base /jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.base/java.lang.Double.parseDouble(Double.java:543) at com.example.java.Main.main(Main.java) :13)

Ord*_*ous 5

您的代码的问题在于您在已经尝试解析它之后进行了很好的检查。

您的主要线索是您获得的堆栈跟踪。它清楚地表明异常是在parseDouble第 13 行抛出的。这是在你自己检查之前,程序永远不会到达它。

您的下一步应该是检查 JavadocDouble.parseDouble以查看它返回什么以及何时抛出。

文档阅读(我遗漏了一些与问题无关的内容):

Returns a new double initialized to the value represented by the specified String

Throws:
    NullPointerException - if the string is null
    NumberFormatException - if the string does not contain a parsable double.
Run Code Online (Sandbox Code Playgroud)

这意味着,如果你使用这个方法来解析你的双打,那么它抛出无效的输入。

你接下来做什么取决于你的目标是什么。抛出异常的 2 个主要问题是:
- 您想要自定义异常,而不是默认异常
- 您想要避免额外异常(以免生成堆栈跟踪等)

如果您属于第一类,那么解决方案很简单 - 将其parseDouble放入try块中,如果失败则重新抛出自定义异常,如下所示:

double d1;
try {
    d1 = Double.parseDouble(input1);
catch (NumberFormatException | NullPointerException e) {
    throw new MyCustomException("Please enter a valid double!", e);
}
Run Code Online (Sandbox Code Playgroud)

如果你这样做,那么你不需要再次检查你的 try/switch 块(你已经保证输入是一个有效的类型!)

如果您想NumberFormatException完全避免,那么最好的办法是遵循Javadoc上的建议,并在尝试解析之前使用 rege 预先检查字符串。