Reputation: 111
I am writing a program using java swing in a form to validate the user's input. I want to make sure the user enters a valid phone number using regex. The code must be done using a try/catch block, not if/else. I was wondering if I was on the right track.
String phone = phoneField.getText();
String regexStr = "^(1\\-)?[0-9]{3}\\-?[0-9]{3}\\-?[0-9]{4}$";
phoneDisplay.setText(phone);
try {
// valid function goes here
phone = "^(1\\-)?[0-9]{3}\\-?[0-9]{3}\\-?[0-9]{4}$";
}
catch {
JOptionPane.showMessageDialog(null,"Please enter a valid phone number");
}
Upvotes: 1
Views: 4967
Reputation: 2738
I totally agree with @Squla that in the described situation is better not to raise an exception and could be better to just use the conditional to show the message using the JOptionPanel.
I want to provide an answer where could be better to use an exception, the idea is that you could have a method or a utility class that you use to verify the numbers in your application and you raise an exception when the phone number is not valid. You could raise any exception but is better to create a custom Exception
the reason is that you could use this custom exception to catch only phone errors and to handle the message according to the error.
class PhoneNotValidException extends RuntimeException {
public PhoneNotValidException(String message) {
super(message);
}
}
public void validatePhoneNumber(String phone) {
final String regexStr = "^(1\\-)?[0-9]{3}\\-?[0-9]{3}\\-?[0-9]{4}$";
if (!Pattern.matches(regexStr, phone)) {
throw new PhoneNotValidException(phone);
}
}
And you could call this method in any part of your application for example when the home phone number change.
public void onHomePhoneChangeListener(ChangeEvent event) {
String phone = "223-32-23";
try {
validatePhoneNumber(phone);
//more code maybe update the database
} catch(PhoneNotValidException pe) {
JOptionPane.showMessageDialog(null,"Please enter a valid phone number");
} catch(Exception ex) {
System.err.println("Other error different that Phone not valid");
}
}
Note that you use the specific PhoneNotValidException
to handle the errors related to the phone not valid and you could handle any other error in a different way.
Upvotes: 1
Reputation: 29
IMO you shouldnt use exception to validate fields, anyway look at this very simple example:
try{
if(!isValid()){
throw new IllegalArgumentException("unvalid");
}
}catch(IllegalArgumentException e){
System.out.println(e.getMessage());
}
Upvotes: 2