Bird
Raised Fist0
Javaprogramming~20 mins

Throw keyword in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Throw Keyword Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Java code using throw?
Consider the following Java code snippet. What will be printed when it runs?
Java
public class TestThrow {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be at least 18");
        } else {
            System.out.println("Access granted");
        }
    }
    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
AAge must be at least 18
BException in thread "main" java.lang.IllegalArgumentException: Age must be at least 18
CAccess granted
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Look at what happens when age is less than 18 and how the exception is handled.
❓ Predict Output
intermediate
2:00remaining
What happens when throw is used without catch?
What will be the output or result of this Java program?
Java
public class ThrowWithoutCatch {
    public static void main(String[] args) {
        throw new RuntimeException("Error occurred");
    }
}
AProgram compiles but throws RuntimeException and terminates with stack trace
BProgram runs silently with no output
CCompilation error: unhandled exception
DProgram prints: Error occurred
Attempts:
2 left
πŸ’‘ Hint
RuntimeException is unchecked. What happens if it is thrown but not caught?
πŸ”§ Debug
advanced
2:00remaining
Identify the error in this throw usage
This Java code tries to throw an exception. What is the error?
Java
public class ThrowError {
    public static void main(String[] args) {
        throw new Exception("Checked exception");
    }
}
ASyntax error: throw keyword used incorrectly
BCompilation error: unhandled checked exception
CRuntime error: Exception thrown but not caught
DNo error, code runs fine
Attempts:
2 left
πŸ’‘ Hint
Exception is a checked exception. What does Java require for checked exceptions?
🧠 Conceptual
advanced
2:00remaining
What is the effect of throw inside a method?
When a method uses the throw keyword to throw an exception, what happens immediately after the throw statement executes?
AThe method pauses and waits for user input
BThe method continues executing the next statement after throw
CThe method terminates immediately and control transfers to the nearest catch block
DThe method restarts from the beginning
Attempts:
2 left
πŸ’‘ Hint
Think about what throw does to the normal flow of a program.
❓ Predict Output
expert
3:00remaining
What is the output of nested throw and catch blocks?
Analyze the output of this Java program with nested try-catch and throw statements.
Java
public class NestedThrowCatch {
    public static void main(String[] args) {
        try {
            try {
                throw new IllegalArgumentException("Inner exception");
            } catch (NullPointerException e) {
                System.out.println("Caught NullPointerException");
            }
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
ACaught NullPointerException
BCompilation error due to nested try-catch
CNo output, program runs silently
DInner exception
Attempts:
2 left
πŸ’‘ Hint
Which catch block matches the thrown exception type?

Practice

(1/5)
1.

What does the throw keyword do in Java?

easy
A. It catches an exception and handles it.
B. It sends an exception to stop normal program flow when an error occurs.
C. It declares a method can throw exceptions.
D. It creates a new thread for parallel execution.

Solution

  1. Step 1: Understand the role of throw

    The throw keyword is used to send an exception object explicitly when an error happens.
  2. Step 2: Differentiate from other keywords

    throw does not catch exceptions (that's catch), nor declare exceptions (that's throws), nor create threads.
  3. Final Answer:

    It sends an exception to stop normal program flow when an error occurs. -> Option B
  4. Quick Check:

    throw sends exception = B [OK]
Hint: Remember: throw sends, catch handles exceptions [OK]
Common Mistakes:
  • Confusing throw with throws keyword
  • Thinking throw catches exceptions
  • Mixing throw with thread creation
2.

Which of the following is the correct way to throw a new IllegalArgumentException in Java?

?
easy
A. throws new IllegalArgumentException("Invalid argument");
B. throw IllegalArgumentException("Invalid argument");
C. throw new IllegalArgumentException("Invalid argument");
D. throw new IllegalArgumentException;

Solution

  1. Step 1: Check syntax for throwing exceptions

    To throw an exception, use throw new ExceptionType("message") with parentheses and semicolon.
  2. Step 2: Identify correct option

    throw new IllegalArgumentException("Invalid argument"); uses correct syntax with new, parentheses, and semicolon. Options B and D miss parentheses or new. throws new IllegalArgumentException("Invalid argument"); uses throws which is for method declarations, not throwing.
  3. Final Answer:

    throw new IllegalArgumentException("Invalid argument"); -> Option C
  4. Quick Check:

    throw + new + parentheses = A [OK]
Hint: Throw exceptions with 'throw new ExceptionType()' syntax [OK]
Common Mistakes:
  • Omitting 'new' keyword
  • Using 'throws' instead of 'throw'
  • Missing parentheses after exception class
3.

What will be the output of the following Java code?

public class TestThrow {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("Error happened");
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }
    }
}
medium
A. Error happened
B. RuntimeException
C. Compilation error
D. No output

Solution

  1. Step 1: Analyze the try block

    The code throws a new RuntimeException with message "Error happened".
  2. Step 2: Analyze the catch block

    The catch block catches the exception and prints its message using e.getMessage(), which is "Error happened".
  3. Final Answer:

    Error happened -> Option A
  4. Quick Check:

    Exception message printed = C [OK]
Hint: Catch prints exception message with getMessage() [OK]
Common Mistakes:
  • Expecting exception type name instead of message
  • Thinking code causes compilation error
  • Assuming no output without catch
4.

Identify the error in the following code snippet:

public class Example {
    public static void main(String[] args) {
        throw new Exception("Problem");
    }
}
medium
A. Missing try-catch block or throws declaration for checked exception.
B. Incorrect exception message format.
C. Cannot throw exceptions in main method.
D. Exception class does not exist.

Solution

  1. Step 1: Identify exception type

    The code throws Exception, which is a checked exception in Java.
  2. Step 2: Check handling of checked exceptions

    Checked exceptions must be either caught in a try-catch block or declared with throws in the method signature. This code does neither, causing a compile error.
  3. Final Answer:

    Missing try-catch block or throws declaration for checked exception. -> Option A
  4. Quick Check:

    Checked exceptions need handling = D [OK]
Hint: Checked exceptions require try-catch or throws declaration [OK]
Common Mistakes:
  • Ignoring checked exception rules
  • Thinking main cannot throw exceptions
  • Confusing checked and unchecked exceptions
5.

Consider this method that throws an exception if the input is negative:

public void checkNumber(int num) {
    if (num < 0) {
        throw new IllegalArgumentException("Negative number not allowed");
    }
    System.out.println("Number is " + num);
}

How should you call this method safely in your code?

hard
A. Use throw keyword again when calling checkNumber.
B. Call checkNumber without any try-catch because IllegalArgumentException is checked.
C. Declare throws IllegalArgumentException in the calling method and do not catch.
D. Call checkNumber inside a try-catch block catching IllegalArgumentException.

Solution

  1. Step 1: Identify exception type thrown

    The method throws IllegalArgumentException, which is an unchecked exception.
  2. Step 2: Decide safe calling practice

    Although unchecked exceptions do not require declaration, to handle errors safely, call the method inside a try-catch block catching IllegalArgumentException.
  3. Final Answer:

    Call checkNumber inside a try-catch block catching IllegalArgumentException. -> Option D
  4. Quick Check:

    Catch unchecked exceptions to handle errors safely = A [OK]
Hint: Catch exceptions even if unchecked for safer code [OK]
Common Mistakes:
  • Thinking unchecked exceptions must be declared
  • Not catching exceptions leading to crashes
  • Misusing throw keyword when calling methods