0
0
JUnittesting~10 mins

assertThrows for exceptions in JUnit - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AIllegalArgumentException
BIOException
CNullPointerException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different exception class than the one thrown.
Forgetting to add .class after the exception name.
2fill in blank
medium

Complete 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'
AIllegalStateException
BNullPointerException
CArrayIndexOutOfBoundsException
DArithmeticException
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception class like NullPointerException.
Not matching the exception type thrown by the code.
3fill in blank
hard

Fix 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'
AIndexOutOfBoundsException
BIllegalArgumentException
CNullPointerException
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Using NullPointerException instead of IndexOutOfBoundsException.
Forgetting to specify the correct exception class.
4fill in blank
hard

Fill 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'
ANumberFormatException
B"abc"
C"123"
DIllegalArgumentException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a valid number string like "123" which does not throw exception.
Using the wrong exception class.
5fill in blank
hard

Fill 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'
AIllegalArgumentException
C"Invalid input"
D"Error"
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.