Exceptions. Practical Tasks
Make WrongPasswordException a subclass of WrongLoginException, and the line catch (WrongLoginException | WrongPasswordException e) stops compiling: Alternatives in a multi-catch statement cannot be related by subclassing. The fix is to extend both classes from Exception directly — and details like this show up in your own solutions on this page, not just in the theory.
These Java exceptions exercises practice the module «Exceptions»: you will write custom exception classes, throw them with the throw statement, catch them in one multi-catch block, and then use the login and password check for user registration in the Online Shop project (part 7). Both tasks have hints, and the section after the tasks lists the bugs that most often break a working-looking solution.
What to Review Before You Start
Both tasks need three skills: declaring your own exception class, throwing it with throw, and catching it in try-catch. If any of them feels shaky, open the matching lesson section from the table first — each rule is explained there with a runnable example.
| Lesson | What you need from it in the tasks |
|---|---|
| How to Create a Custom Exception in Java | The classes WrongLoginException and WrongPasswordException with two constructors |
| throw and throws in Java | Throwing an exception when the login or the password is invalid |
| try-catch: Multi-Catch | Catching both exceptions in one multi-catch block |
| Checked vs Unchecked Exceptions | Choosing the parent class: Exception (checked) or RuntimeException |
| Exceptions in Java | What happens to an exception that nobody catches |
Login and Password Validation
- Create a static method that takes three parameters:
login,passwordandconfirmPassword. loginmust contain only Latin letters, digits and the underscore.- The length of
loginmust be less than 20 characters (1 to 19; an empty string is invalid). Iflogindoes not meet these requirements, throwWrongLoginException. passwordmust contain only Latin letters, digits and the underscore, and its length must be less than 20 characters.passwordandconfirmPasswordmust also be equal. Ifpassworddoes not meet these requirements, throwWrongPasswordException.WrongPasswordExceptionandWrongLoginExceptionare custom exception classes with two constructors: a default one, and one that takes the exception message and passes it to the constructor ofException.- Handle the exceptions inside the method.
- Use a multi-catch block.
- The method returns
trueif the values are valid, andfalseotherwise.
Where to start
Put all the checks in a try block and, when a rule is broken, throw an exception with throw and a clear message, for example "Login must be shorter than 20 characters". Catch both exceptions with one catch (WrongLoginException | WrongPasswordException e), print e.getMessage() and return false. To check the characters, login.matches("[A-Za-z0-9_]+") is enough.
Registration and Login Error Handling
Online Store · part 7 of 7 · ← part 6
Implement authentication and registration of an online shop user:
- Store registered users in a
Mapof login–password pairs. - If the user enters a login and password that are in the map, the user is authenticated.
- If the login is in the map but the password does not match, report a login error. Do not change the existing entry.
- If the login is not in the map, ask for the password once more (
confirmPassword) and validate the data with the method from the task «Login and Password Validation». - If the validation passes, add the login and password to the map — the user is registered.
Where Solutions Break
Most solutions to these tasks fail not on exceptions but on string checks: find() instead of matches() lets invalid characters through, \w rejects letters such as é, and == compares string references instead of contents. Here is a short snippet with its real output:
Pattern p = Pattern.compile("[A-Za-z0-9_]+");
System.out.println(p.matcher("admin!").find()); // true - found the substring "admin"
System.out.println(p.matcher("admin!").matches()); // false - the whole string is checked
System.out.println("admin_1".matches("\\w+")); // true
System.out.println("josé".matches("\\w+")); // false - \w is only [a-zA-Z_0-9] by default
System.out.println("".matches("[A-Za-z0-9_]+")); // false - the + quantifier needs at least one character
System.out.println(new String("qwerty") == "qwerty"); // false - two different objects | Mistake | What happens | How to fix it |
|---|---|---|
matcher(login).find() | The login admin! passes the check | Use matches() or String.matches() |
password == confirmPassword | Works in a test with string literals (they are interned), but returns false for equal passwords read from Scanner | password.equals(confirmPassword) |
login.length() <= 20 | A 20-character login is accepted, although the task requires fewer than 20 characters | login.length() < 20 |
No check for null | login.matches(...) throws NullPointerException, the multi-catch does not catch it, and the method crashes instead of returning false | Check login == null first and throw WrongLoginException |
users.put(login, password) without containsKey() | The password of an existing user is silently overwritten | Check whether the login is already in the Map first |
Check your code
Before you call a task done, go through the code style checklist: exception class names end with Exception, every throw carries a clear message, and there are no empty catch blocks.
Frequently Asked Questions
Should WrongLoginException extend Exception or RuntimeException?
Extend Exception. A wrong login or password is an expected input error that the calling code can react to, so the exception should be checked: the compiler will force callers to catch it or declare it in throws. RuntimeException is for programming errors. The tasks on this page require Exception; the full comparison is in Extends Exception vs extends RuntimeException.
Should a validation method catch its own exceptions or declare them in throws?
In the first task the method catches them itself and returns a boolean, because the task says so. In real code a validator usually declares throws WrongLoginException, WrongPasswordException and lets the caller decide what to show the user: a plain true/false loses the reason why the input was rejected.
Can I assign a new value to the variable e in a multi-catch block?
No. The parameter of a multi-catch block is implicitly final, so e = new WrongLoginException() inside catch (WrongLoginException | WrongPasswordException e) fails with multi-catch parameter e may not be assigned. In a catch block with a single type such an assignment is allowed.
Can I store passwords in a Map in a real application?
Only in a training task. Real systems never store plain-text passwords: they store a salted hash (bcrypt, PBKDF2, Argon2), compare hashes on login and keep users in a database, not in memory.
Comments