如何在Java中使用try-catch?

时间:2016-08-26 13:42:52

标签: exception exception-handling

我正在尝试学习try和catch块,但是下面的代码缺少了一些东西,而且我的代码没有给出catch块中给出的自定义错误。这有什么问题?

这是我的代码:

package com.example.java;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {

    int num1;
    int num2;
    String operatorValue;

    System.out.println("Please Enter First Number :");
    Scanner firstInput = new Scanner(System.in);
    num1 = firstInput.nextInt();

    System.out.println("Please Enter Second Number :");
    Scanner secondInput = new Scanner(System.in);
    num2 = secondInput.nextInt();

    System.out.println("Please Select operation + - * / % :");
    Scanner operatorInput = new Scanner(System.in);
    operatorValue = operatorInput.nextLine();

    double results = 0;

    try {
        switch (operatorValue) {
            case "+":
                results = num1 + num2;
                break;
            case "-":
                results = num1 - num2;
                break;
            case "*":
                results = num1 * num2;
                break;
            case "/":
                results = num1 / num2;
                break;

            case "%":
                results = num1 % num2;
                break;

            default:
                System.out.println("please Enter a valid operator value");
                return;

        }System.out.println("The Result is :"+ results);
    } catch (Exception e) {
        System.out.println("please enter a valid number "+ e.getMessage());
    }
}
}

1 个答案:

答案 0 :(得分:0)

您的try...catch块不包含输入部分。这是有问题的部分,因此将其包装而不是计算:

int num1;
int num2;
String operatorValue;

try {
    System.out.println("Please Enter First Number :");
    Scanner firstInput = new Scanner(System.in);
    num1 = firstInput.nextInt(); // can produce error

    System.out.println("Please Enter Second Number :");
    Scanner secondInput = new Scanner(System.in);
    num2 = secondInput.nextInt(); // can produce error


    System.out.println("Please Select operation + - * / % :");
    Scanner operatorInput = new Scanner(System.in);
    operatorValue = operatorInput.nextLine();

} catch (Exception e) {
    System.out.println("please enter a valid number "+ e.getMessage());
}

// Rest of code