If you want to throw the exception when it does not match the pattern, then you need to throw it explicitly. The signature of matches
method is
public boolean matches(String regex)
This means it will return true
or false
so if your pattern matches the string input, then it will return true
or it will return false
.
To solve your problem, you can do,
if(test1.matches("(d+)(p/)(d+)")){
// domeSomething
}else {
throw new NumberFormatException();
}
This is the case where you have to use try-catch
, if you don't want to use it,
then you can simply show MessageDialog
as follows
if(test1.matches("(d+)(p/)(d+)")){
//doSomething
}else{
JOptionPane.showMessageDialog(null, e.getMessage(), "ALERT!", JOptionPane.ERROR_MESSAGE);
}