in java,
is it possible to check a string has special characters or letters on it and if so throw an exception?
something like this but using try/catch
/** Get and Checks if the ssn is valid or not **/
private String getSSN(){
String tempSSN;
tempSSN = scan.nextLine();
if(tempSSN.matches("^.*[^a-zA-Z ]{9}.*$") == false){
System.out.print("enter a valid SSN without spaces or dashes.");
tempSSN= scan.nextLine();
}
return tempSSN;
}
If you can do it without exception handling, there is no obvious reason for why you would use a
try-catchblock. But if you want to throw an exception, it’s not a must to use a try-catch block. You can usethrow.You can use a
catchblock if you want to catch an exception and log any error or message and continue the execution. Or you catch an exception when you want to throw other meaningful exception.