Search the courses, subjects, tracks, games and features, or jump straight to a page.
5 cards from this section. Quick, good the night before a test.
Write the single statement that manually raises an ArithmeticException with the message "Invalid input", and explain what each part of it does.
The pattern from the lesson is throw new ExceptionType("message");
In the lesson's example, age is 15 and the program ends by printing Exception in thread "main" java.lang.ArithmeticException: You are underaged!. Which line causes this, and why does the program stop instead of carrying on?
Look at the if condition, then ask whether any catch block is waiting for the exception.
Which keyword manually raises an exception?
It is the keyword that appears together with new.
Which statement correctly raises an exception?
An object has to exist before it can be thrown.
Build a validator for a registration form. Write validateUsername(String name) that throws an IllegalArgumentException when the name is empty, shorter than 3 characters, or contains a space, each with its own message. In main, test "anjali_07", "", "ab", "ravi kumar" and "dev2024", printing a success message or the error message for each one. Two String methods help: name.isEmpty() returns true when the string has no characters at all, and name.contains(" ") returns true when the string has a space anywhere in it.
Order the checks from the most basic (empty) to the most specific, and throw as soon as one fails.
A temperature sensor sometimes sends impossible readings. Create a custom SensorException and a method readTemperature(int raw) that throws it when a reading is outside -50 to 150. Process the readings 23, 25, 999, 24, -80 and 26: print each valid reading, skip each invalid one with a message, and finally print how many readings were valid and invalid and the average of the valid ones.
Anything after the call in the try block is skipped for a bad reading, which is exactly what keeps it out of the total.
6 more questions in this section. Enroll free to practise them all.
Enroll free