java - try/catch block not working in actionlistener -


i working on 2 programs school, 1 take contact info , save text file , other read text file. works have add try/catch block program takes input catch non-numeric entries in age text field. have been trying many different ways of doing since yesterday , nothing has been working. below code. if can point me in right direction grateful because feel there fundamental not getting here. thanks

  private class savedata implements actionlistener{     public void actionperformed(actionevent e){              string age1 = (string)agefield.gettext();             int age = integer.parseint(age1);              try{                 int = age;             }             catch(inputmismatchexception e1){                 joptionpane.showmessagedialog(null, "please enter     integer");             }              string name = (string)namefield.gettext();             string email = (string)emailfield.gettext();             string cell = (string)cellfield.gettext();                if(age>= 0 && age<=120){                 outputfile.println("name: " + name);                 outputfile.println("age: " + age);                 outputfile.println("email: " + email);                 outputfile.println("cell #: " +cell);                 outputfile.println("---------------------------");                  namefield.settext("");                 agefield.settext("");                 emailfield.settext("");                 cellfield.settext("");             }             else{                 joptionpane.showmessagedialog(null, "you have entered invalid age \n " +                                         "please enter age between 0 , 120",                                                 "age entry error",      joptionpane.error_message);                  namefield.settext("");                 agefield.settext("");                 emailfield.settext("");                 cellfield.settext("");             }//end else         }//end actionperformed     }//end actionlistener 

so see 3 problems(including ones aren't having problems with- yet):

  • the function parseint throws exception not catching because not in try block.
  • you catching wrong exception never caught. can read javadoc exception here.
  • the variable age unreachable outside of try/catch block due scoping rules.

here how should it:

string age1 = (string)agefield.gettext(); int age = -1;//always assign variable default value try{ age = integer.parseint(age1); } catch(numberformatexception err){ joptionpane.showmessagedialog(null, "please enter valid integer!"); }

final thought, if catching exception, should display error (which doing) , return function. there should return in catch block, don't want continue execute further code. fail because expects valid age value.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -