Skip to content
Advertisement

how pattern syntax exception works

JavaScript

how do I use the following statement in try n catch block to chk if the name is valid and display error msg if any?

JavaScript

and how to use PatternSyntaxException

Advertisement

Answer

You don’t need a try...catch to check if the name is valid. The line you wrote: NAME_PATTERN.matcher(name).matches() returns a boolean, true if it matches and false if it doesn’t. So you can check this boolean in a if...else block:

JavaScript

The PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern. This means that if your NAME_REGEX regex has a syntax error then when you call Pattern.compile(NAME_REGEX) this exception will be thrown.

You can try...catch it like:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement