Throw keyword in Java - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
Let's see how the throw keyword affects the time a program takes to run.
We want to know if throwing an exception changes how long the code runs as input grows.
Analyze the time complexity of the following code snippet.
public void checkNumber(int n) {
if (n < 0) {
throw new IllegalArgumentException("Negative number");
}
System.out.println("Number is " + n);
}
This code checks if a number is negative and throws an exception if it is.
Look for loops or repeated steps that take time as input grows.
- Primary operation: A simple if-check and possibly throwing an exception.
- How many times: The check happens once per call; no loops or recursion.
The time to run this code does not increase with the size of the input number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check, maybe 1 throw |
| 100 | 1 check, maybe 1 throw |
| 1000 | 1 check, maybe 1 throw |
Pattern observation: The number of steps stays the same no matter how big the number is.
Time Complexity: O(1)
This means the time to run the code stays constant, no matter the input size.
[X] Wrong: "Throwing an exception makes the program slower as input grows."
[OK] Correct: Throwing an exception happens instantly when the condition is met and does not depend on input size.
Understanding that throwing exceptions does not add loops or repeated work helps you explain code efficiency clearly and confidently.
"What if the code checked every element in a list and threw an exception on the first negative number? How would the time complexity change?"
Practice
What does the throw keyword do in Java?
Solution
Step 1: Understand the role of
Thethrowthrowkeyword is used to send an exception object explicitly when an error happens.Step 2: Differentiate from other keywords
throwdoes not catch exceptions (that'scatch), nor declare exceptions (that'sthrows), nor create threads.Final Answer:
It sends an exception to stop normal program flow when an error occurs. -> Option BQuick Check:
throwsends exception = B [OK]
- Confusing throw with throws keyword
- Thinking throw catches exceptions
- Mixing throw with thread creation
Which of the following is the correct way to throw a new IllegalArgumentException in Java?
?
Solution
Step 1: Check syntax for throwing exceptions
To throw an exception, usethrow new ExceptionType("message")with parentheses and semicolon.Step 2: Identify correct option
throw new IllegalArgumentException("Invalid argument"); uses correct syntax withnew, parentheses, and semicolon. Options B and D miss parentheses ornew. throws new IllegalArgumentException("Invalid argument"); usesthrowswhich is for method declarations, not throwing.Final Answer:
throw new IllegalArgumentException("Invalid argument"); -> Option CQuick Check:
throw + new + parentheses = A [OK]
- Omitting 'new' keyword
- Using 'throws' instead of 'throw'
- Missing parentheses after exception class
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());
}
}
}Solution
Step 1: Analyze the try block
The code throws a newRuntimeExceptionwith message "Error happened".Step 2: Analyze the catch block
The catch block catches the exception and prints its message usinge.getMessage(), which is "Error happened".Final Answer:
Error happened -> Option AQuick Check:
Exception message printed = C [OK]
- Expecting exception type name instead of message
- Thinking code causes compilation error
- Assuming no output without catch
Identify the error in the following code snippet:
public class Example {
public static void main(String[] args) {
throw new Exception("Problem");
}
}Solution
Step 1: Identify exception type
The code throwsException, which is a checked exception in Java.Step 2: Check handling of checked exceptions
Checked exceptions must be either caught in a try-catch block or declared withthrowsin the method signature. This code does neither, causing a compile error.Final Answer:
Missing try-catch block or throws declaration for checked exception. -> Option AQuick Check:
Checked exceptions need handling = D [OK]
- Ignoring checked exception rules
- Thinking main cannot throw exceptions
- Confusing checked and unchecked exceptions
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?
Solution
Step 1: Identify exception type thrown
The method throwsIllegalArgumentException, which is an unchecked exception.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 catchingIllegalArgumentException.Final Answer:
CallcheckNumberinside a try-catch block catchingIllegalArgumentException. -> Option DQuick Check:
Catch unchecked exceptions to handle errors safely = A [OK]
- Thinking unchecked exceptions must be declared
- Not catching exceptions leading to crashes
- Misusing throw keyword when calling methods
