Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to assert that a NullPointerException is thrown.
JUnit
assertThrows([1].class, () -> { throw new NullPointerException(); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different exception class than the one thrown.
Forgetting to add .class after the exception name.
✗ Incorrect
The assertThrows method expects the exception class that should be thrown. Here, NullPointerException.class is correct.
2fill in blank
mediumComplete the code to assert that an ArithmeticException is thrown when dividing by zero.
JUnit
assertThrows([1].class, () -> { int result = 10 / 0; });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception class like NullPointerException.
Not matching the exception type thrown by the code.
✗ Incorrect
Dividing by zero throws an ArithmeticException, so assertThrows should expect ArithmeticException.class.
3fill in blank
hardFix the error in the code to correctly assert that an IndexOutOfBoundsException is thrown.
JUnit
assertThrows([1].class, () -> { List<String> list = new ArrayList<>(); list.get(1); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using NullPointerException instead of IndexOutOfBoundsException.
Forgetting to specify the correct exception class.
✗ Incorrect
Accessing an invalid index in a list throws IndexOutOfBoundsException, so assertThrows should expect IndexOutOfBoundsException.class.
4fill in blank
hardFill both blanks to assert that a NumberFormatException is thrown when parsing an invalid number.
JUnit
assertThrows([1].class, () -> { Integer.parseInt([2]); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a valid number string like "123" which does not throw exception.
Using the wrong exception class.
✗ Incorrect
Parsing "abc" as an integer throws NumberFormatException, so the first blank is NumberFormatException.class and the second blank is the invalid string "abc".
5fill in blank
hardFill all three blanks to assert that an IllegalArgumentException is thrown with a custom message.
JUnit
IllegalArgumentException exception = assertThrows([1].class, () -> { throw new [2]([3]); }); assertEquals("Invalid input", exception.getMessage());
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different exception classes in assertThrows and throw statement.
Passing a wrong message string that does not match the assertion.
✗ Incorrect
To assert the exception and check its message, use IllegalArgumentException.class for the first blank, throw new IllegalArgumentException for the second, and pass the message "Invalid input" as the third.