Discuss / Java / 练习:用try ... catch捕获异常并处理

练习:用try ... catch捕获异常并处理

Topic source

韦雪松

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {
    public static void main(String[] args) {
        String a = "12";
        String b = "x9";
        // TODO: 捕获异常并处理
        int c = stringToInt(a);
        int d = stringToInt(b);
        System.out.println(c * d);
    }

    static int stringToInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(s + " is not integer");
        }
    }
}

  • 1

Reply