简体   繁体   English

关于Java try-catch异常处理

[英]about java try-catch exception handling

Why there is an exception throwed out while there is nothing to deal wit in my try block? 为什么在try块中没有什么可以处理的情况下抛出异常?

When I input some string type content,throws out a "Exception in thread "main" 当我输入一些字符串类型的内容时,抛出“线程“ main”中的异常”

java.lang.NumberFormatException: For input string: "ss"" java.lang.NumberFormatException:对于输入字符串:“ ss”

import java.io.*;

public class Strinput {
    public static void main(String args[]) {
        String s1 = null, s2 = null, ss, si, sf;
        int i1, i2;
        float f1, f2;
        BufferedReader strin = new BufferedReader(new InputStreamReader(
                System.in));
        // please ignore the printing language
        try {
            System.out.print("输入第一个字符串:");
            s1 = strin.readLine();
            System.out.print("输入第二个字符串:");
            s2 = strin.readLine();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        i1 = Integer.parseInt(s1);
        i2 = Integer.parseInt(s2);
        f1 = Float.parseFloat(s1);
        f2 = Float.parseFloat(s2);
        ss = strAdd(s1, s2);
        si = strAdd(i1, i2);
        sf = strAdd(f1, f2);
        System.out.println("输入的二个字符串相加结果为:" + ss);
        System.out.println("输入字符串转换为整数相加结果为:" + si);
        System.out.println("输入字符串转换为浮点数相加结果为:" + sf);
    }

    static String strAdd(String str1, String str2) {
        return str1 + str2;
    }

    static String strAdd(int int1, int int2) {
        return String.valueOf(int1 + int2);
    }

    static String strAdd(float flt1, float flt2) {
        return String.valueOf(flt1 + flt2);
    }
}

The exception is thrown after your try/catch! 尝试/捕获引发异常!

It happens because you can't convert the string value "ss" within s1 into a number. 发生这种情况是因为您无法将s1中的字符串值“ ss”转换为数字。

The real answer: focus on reading those exception messages: they exactly tell you where the problem is and what caused it. 真正的答案:专注于阅读那些异常消息:它们准确地告诉您问题出在哪里以及引起问题的原因。 It is all in front of your eyes. 一切都在您眼前。 And beyond that: such RuntimeExceptions can show up anywhere in your code, they are not restricted to the places where you put down a try/catch! 不仅如此:这样的RuntimeExceptions可以显示在代码中的任何地方,它们不仅限于您放置try / catch的地方!

i think 我认为

BufferedReader strin = new BufferedReader(new InputStreamReader(
            System.in));

in the block try/catch 在块try / catch中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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