简体   繁体   中英

How to handle error number format exception :For input string: “”

I'm doing a simple insert in one form.

  1. no_text & no_text_external were choose from drop down
  2. I'm saving the id for no_text & no_text_external in another table which is

dbname_m_db

and would like to view it back. So i'm doing 4 test which are

test1: insert no_text

test2: insert no_text_external

test3: insert no_text & no_text_external

test4: not insert both

so the result is, only test3 is success to view it back. while the other 3 return error number format exception :For input string: "" . I don't know the best way to filter it. Here the code that im working for. Any idea?

    public void getDataById(Connection con){

    try{
        ps = con.createStatement();

        rs = ps.executeQuery("SELECT * FROM "+ dbname_m_db +" WHERE id_m_db ='"+ this.getId_m_db() +"' AND status_data ='1'");

        while (rs.next()) {
            this.setNo_text(rs.getString("no_text"));
            this.setNo_text_external(rs.getString("no_text_external"));
        }
            int int_no_text = Integer.valueOf(this.getNo_text());
            int int_no_text_external = Integer.valueOf(this.getNo_text_external());
            this.setNo_text_value(au.getTextById(con, int_no_text));
            this.setNo_text_external_value(au.getTextExternalById(con, int_no_text_external));

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

In order to handle the NumberFormatException error, you should validate your String before executing Integer.valueOf() .

You could validate if your string is empty:

int int_no_text;

if (!this.getNo_text().isEmpty) {
    int_no_text = Integer.valueOf(this.getNo_text());
}

Honestly, I'm not really fond of this approach because one is neither validating if the string is null or if it contains, in fact, an integer.

Therefore, one could make use of a really good utility class, NumberUtils , and validate if we're on a presence of a number:

int int_no_text;

if (NumberUtils.isNumber(this.getNo_text())) {
    int_no_text = Integer.valueOf(this.getNo_text());
}

Basically, this way one checks whether the string is a valid Java number hence null and empty/blank strings will return false.

It looks like you're passing an empty string when you are getting the integer value from the table. I would check to make sure that you're getting he expected return from the table before converting it into an int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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