Here is checkPass method.
boolean checkPass(String password){
if (password.length() > 2 && password.charAt(4) != ' ') return true;
else return false;
}
password value must create exception
boolean password = checkPass("");
CodePudding user response:
If I understand your question correctly, you want to throw exception when the input is empty.
boolean checkPass(String password) throws Exception {
if (password == null || password.isEmpty()) {
throw new Exception("password should not be empty.");
}
if (password.length() > 2 && password.charAt(4) != ' ') return true;
else return false;
}
CodePudding user response:
Do you mean to make compilation fail when it encounters code like checkPass("")
?
I dont think that Java has static assertions, i.e assertions computed at compile time. Probably, the closest thing you can get is to use a tool like Findbugs to statically analyze your code.
Of course, you can also use unit tests, but these are actually runtime checks (which are run just after the compilation phase, but before deploying the code to a production site).
CodePudding user response:
You can change the method return type to void
from boolean
and throw an Exception
in case your condition is not satisfied.
void checkPass(String password) throws Exception{
if (password.length() > 2 && password.charAt(4) != ' ') {
//do nothing
} else {
throw new Exception("check pass failed");
}
}
You can then use checkPass("");
method to create an Exception.