Bird
Raised Fist0
JUnittesting~20 mins

assertThrows for exceptions in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
AssertThrows Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the result of this JUnit test using assertThrows?
Consider the following JUnit 5 test method. What will be the test execution result?
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

class Calculator {
    int divide(int a, int b) {
        return a / b;
    }
}

public class CalculatorTest {
    @Test
    void testDivideByZero() {
        Calculator calc = new Calculator();
        assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
    }
}
ATest passes because ArithmeticException is thrown as expected.
BTest fails because no exception is thrown.
CTest fails because NullPointerException is thrown instead.
DTest fails due to a compilation error in the test code.
Attempts:
2 left
💡 Hint
Think about what happens when dividing by zero in Java.
❓ assertion
intermediate
2:00remaining
Which assertThrows usage correctly verifies NullPointerException?
You want to test that calling method process(null) throws NullPointerException. Which assertThrows statement is correct?
JUnit
class Processor {
    void process(String input) {
        if (input == null) throw new NullPointerException();
    }
}
AassertThrows(NullPointerException.class, () -> processor.process("text"));
BassertThrows(Exception.class, () -> processor.process(null));
CassertThrows(IllegalArgumentException.class, () -> processor.process(null));
DassertThrows(NullPointerException.class, () -> processor.process(null));
Attempts:
2 left
💡 Hint
The exception type must match exactly the one thrown.
🔧 Debug
advanced
2:00remaining
Why does this assertThrows test fail unexpectedly?
Examine the test below. It is supposed to check that getItem(-1) throws IndexOutOfBoundsException, but the test fails. Why?
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import java.util.List;

public class ListTest {
    @Test
    void testGetItem() {
        List<String> list = List.of("a", "b", "c");
        assertThrows(IndexOutOfBoundsException.class, () -> list.get(1));
    }
}
AThe test fails because List.of creates a mutable list that throws a different exception.
BThe test fails because list.get(1) returns "b" and does not throw an exception.
CThe test fails because IndexOutOfBoundsException is not the correct exception type.
DThe test fails because assertThrows requires a try-catch block around the lambda.
Attempts:
2 left
💡 Hint
Check the index used in list.get and the list size.
🧠 Conceptual
advanced
2:00remaining
What does assertThrows return and how can it be used?
In JUnit 5, assertThrows returns the caught exception. How can this feature be used in tests?
ATo automatically retry the test if the exception occurs.
BTo suppress the exception so the test continues without failure.
CTo verify the exception message or properties after catching it.
DTo convert checked exceptions into unchecked exceptions.
Attempts:
2 left
💡 Hint
Think about what you can do with the exception object after catching it.
❓ framework
expert
2:00remaining
How to test a method that throws a checked exception using assertThrows?
Given a method that throws IOException, which assertThrows usage correctly tests it?
JUnit
import java.io.IOException;

class FileReader {
    void readFile(String path) throws IOException {
        if (path == null) throw new IOException("Path is null");
    }
}
AassertThrows(IOException.class, () -> { fileReader.readFile(null); });
BassertThrows(Exception.class, () -> fileReader.readFile(null));
CassertThrows(IOException.class, () -> fileReader.readFile(null));
DassertThrows(IOException.class, () -> fileReader.readFile("file.txt"));
Attempts:
2 left
💡 Hint
Checked exceptions require handling or declaration in lambda.

Practice

(1/5)
1. What is the main purpose of assertThrows in JUnit testing?
easy
A. To check if a specific exception is thrown by a block of code
B. To verify the return value of a method
C. To measure the execution time of a method
D. To skip a test case conditionally

Solution

  1. Step 1: Understand the role of assertThrows

    assertThrows is designed to check if a certain exception occurs when running some code.
  2. Step 2: Compare with other options

    Options B, C, and D describe different test functions unrelated to exception checking.
  3. Final Answer:

    To check if a specific exception is thrown by a block of code -> Option A
  4. Quick Check:

    assertThrows checks exceptions = A [OK]
Hint: Remember: assertThrows tests exceptions thrown by code [OK]
Common Mistakes:
  • Confusing assertThrows with assertEquals
  • Thinking assertThrows measures performance
  • Using assertThrows to skip tests
2. Which of the following is the correct syntax to use assertThrows in JUnit 5?
easy
A. assertThrows(Exception.class, () -> methodCall());
B. assertThrows(() -> methodCall(), Exception.class);
C. assertThrows(methodCall(), Exception.class);
D. assertThrows(Exception.class, methodCall());

Solution

  1. Step 1: Recall the method signature

    The correct syntax is assertThrows(Exception.class, executable) where executable is a lambda or method reference.
  2. Step 2: Check each option

    assertThrows(Exception.class, () -> methodCall()); matches the correct order and lambda usage. Options A, B, and D have wrong argument order or missing lambda.
  3. Final Answer:

    assertThrows(Exception.class, () -> methodCall()); -> Option A
  4. Quick Check:

    Exception class first, then lambda = C [OK]
Hint: Exception class first, then lambda with code [OK]
Common Mistakes:
  • Swapping the order of arguments
  • Passing method call instead of lambda
  • Omitting the lambda expression
3. What will be the result of this JUnit test?
import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void testDivideByZero() {
  assertThrows(ArithmeticException.class, () -> {
    int result = 10 / 0;
  });
}
medium
A. Test passes but exception type is wrong
B. Test fails because no exception is thrown
C. Test fails due to syntax error
D. Test passes because ArithmeticException is thrown

Solution

  1. Step 1: Analyze the code inside assertThrows

    The code divides 10 by 0, which throws an ArithmeticException at runtime.
  2. Step 2: Check if exception matches expected

    assertThrows expects ArithmeticException.class, which matches the thrown exception.
  3. Final Answer:

    Test passes because ArithmeticException is thrown -> Option D
  4. Quick Check:

    Exception thrown matches expected = A [OK]
Hint: Divide by zero throws ArithmeticException [OK]
Common Mistakes:
  • Assuming no exception is thrown
  • Confusing exception types
  • Thinking test fails on exception
4. Identify the error in this JUnit test using assertThrows:
@Test
void testNullPointer() {
  assertThrows(NullPointerException, () -> {
    String s = null;
    s.length();
  });
}
medium
A. Lambda syntax is incorrect
B. NullPointerException is not thrown here
C. Missing .class after NullPointerException
D. assertThrows cannot test NullPointerException

Solution

  1. Step 1: Check the exception argument

    The exception class must be passed as NullPointerException.class, not just the class name.
  2. Step 2: Verify lambda and exception thrown

    The lambda syntax is correct and the code throws NullPointerException as expected.
  3. Final Answer:

    Missing .class after NullPointerException -> Option C
  4. Quick Check:

    Exception class needs .class suffix = B [OK]
Hint: Always add .class after exception name in assertThrows [OK]
Common Mistakes:
  • Omitting .class after exception
  • Miswriting lambda syntax
  • Assuming exception not thrown
5. You want to test that a method parseNumber(String s) throws NumberFormatException only when the input is not a valid number. Which of these tests correctly uses assertThrows to check this behavior?
hard
A. assertThrows(NumberFormatException.class, () -> parseNumber(123));
B. assertThrows(NumberFormatException.class, () -> parseNumber("abc"));
C. assertThrows(Exception.class, () -> parseNumber(null));
D. assertThrows(NumberFormatException.class, () -> parseNumber("123"));

Solution

  1. Step 1: Understand the method behavior

    parseNumber should throw NumberFormatException for invalid strings like "abc" but not for valid numbers like "123".
  2. Step 2: Evaluate each test case

    assertThrows(NumberFormatException.class, () -> parseNumber("abc")); tests invalid input "abc" correctly. assertThrows(NumberFormatException.class, () -> parseNumber("123")); tests valid input, so no exception expected. assertThrows(Exception.class, () -> parseNumber(null)); uses a different exception and null input. assertThrows(NumberFormatException.class, () -> parseNumber(123)); passes an integer instead of string, causing compile error.
  3. Final Answer:

    assertThrows(NumberFormatException.class, () -> parseNumber("abc")); -> Option B
  4. Quick Check:

    Test invalid input throws NumberFormatException = D [OK]
Hint: Test invalid strings with assertThrows for NumberFormatException [OK]
Common Mistakes:
  • Testing valid input expecting exception
  • Passing wrong argument types
  • Using wrong exception class
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard