-3

I am trying to convert a string to an integer but in case it's not possible.

I want that integer variable to have a null value but I keep on getting a null pointer exception when the string is unconvertable while I need it in such case to catch the exception and handle it the way i want which is to put null in the integer variable.

This is my code:

String numt=request.getParameter("telephoneClient");
Integer tel;
try{
    tel=Integer.parseInt(numt);
} catch(NullPointerException ex1)
{
    tel=null;
} catch (NumberFormatException ex2) 
{
    tel=null;
} catch(Exception ex)
{
    tel=null;
}
AntoineB
  • 4,535
  • 5
  • 28
  • 61

1 Answers1

-1

For more information on errors from INteger.parseInt check out this question. To get around a NPE You can do a null check on numt before attempting to parse to Integer.

String numt=request.getParameter("telephoneClient");
Integer tel;
if(null ==numt){
  tel = numt;
  return tel;
}
else{
    try{
        tel=Integer.parseInt(numt);
    } catch(NullPointerException ex1)
    {
        tel=null;
    } catch (NumberFormatException ex2) 
    {
        tel=null;
    } catch(Exception ex)
    {
        tel=null;
    }
}

Added A null check before your try block. if null, tel = null, and return

Akin Okegbile
  • 1,108
  • 19
  • 36