Throwing custom exceptions in Java - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we throw custom exceptions in Java, it's important to understand how this affects the program's running time.
We want to see how the cost of throwing exceptions grows as the program runs.
Analyze the time complexity of the following code snippet.
public class CustomExceptionExample {
public static void checkValue(int value) throws MyException {
if (value < 0) {
throw new MyException("Negative value not allowed");
}
}
}
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
This code checks a value and throws a custom exception if the value is negative.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The check and possible throw happen once per method call.
- How many times: Each call to
checkValueruns this check once; no loops or recursion inside.
Since the method only checks once per call, the time does not increase with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, possibly 0 or some exceptions thrown |
| 100 | 100 checks, exceptions thrown only for negative values |
| 1000 | 1000 checks, same pattern |
Pattern observation: The time grows linearly with the number of calls, but throwing exceptions is a rare event and does not add loops.
Time Complexity: O(n)
This means the time grows directly with how many times you call the method, not with the value size itself.
[X] Wrong: "Throwing an exception inside a method makes the method run slower every time."
[OK] Correct: Exceptions only slow down when actually thrown, not when the method runs normally without throwing.
Understanding how exceptions affect performance helps you write clear and efficient code, a skill valued in many programming tasks.
"What if the method checked a list of values and threw exceptions inside a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand what custom exceptions do
Custom exceptions let programmers define specific error types that describe particular problems clearly.Step 2: Identify the purpose of throwing them
Throwing a custom exception signals a specific error condition, making it easier to catch and handle that error properly.Final Answer:
To create a specific error type with a clear message for better error handling. -> Option CQuick Check:
Custom exceptions improve error clarity = A [OK]
- Thinking exceptions fix errors automatically
- Believing exceptions speed up code
- Assuming exceptions remove need for error handling
MyException?Solution
Step 1: Recall Java syntax for throwing exceptions
In Java, to throw an exception, you use the keywordthrowfollowed bynewand the exception class constructor.Step 2: Match the syntax with the options
Only throw new MyException(); uses the correct syntax:throw new MyException();Final Answer:
throw new MyException(); -> Option AQuick Check:
Throw syntax = throw new Exception() [OK]
- Omitting the 'new' keyword
- Adding extra keywords like 'exception'
- Using parentheses without 'new'
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Test {
public static void check(int num) throws MyException {
if (num < 0) {
throw new MyException("Negative number not allowed");
} else {
System.out.println("Number is " + num);
}
}
public static void main(String[] args) {
try {
check(-5);
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}Solution
Step 1: Analyze the check method behavior
If the input number is less than 0, it throws aMyExceptionwith message "Negative number not allowed"; otherwise, it prints the number.Step 2: Follow the main method execution
Main callscheck(-5), which triggers the exception because -5 < 0. The exception is caught and its message is printed.Final Answer:
Negative number not allowed -> Option AQuick Check:
Exception message printed = C [OK]
- Expecting the number to print despite exception
- Thinking code causes compilation error
- Ignoring exception catch block
class MyException extends Exception {}
public class Demo {
public static void test() {
throw new MyException();
}
}Solution
Step 1: Check method signature for checked exceptions
SinceMyExceptionextendsException(a checked exception), the method must declare it withthrows MyException.Step 2: Identify missing throws declaration
The methodtest()throwsMyExceptionbut does not declare it, causing a compilation error.Final Answer:
Missing 'throws' declaration in method signature. -> Option BQuick Check:
Checked exceptions require 'throws' declaration [OK]
- Forgetting 'throws' in method signature
- Thinking all exceptions are unchecked
- Assuming extending Exception is invalid
InvalidAgeException that should be thrown when age is less than 18. Which of the following code snippets correctly defines and throws this exception inside a method validateAge?Solution
Step 1: Define a checked exception with message constructor
class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); } correctly extendsExceptionand defines a constructor that accepts a message, callingsuper(msg).Step 2: Throw exception with message and declare it
The methodvalidateAgethrowsInvalidAgeExceptionwhen age < 18 and declares it withthrows InvalidAgeException.Final Answer:
class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); } -> Option DQuick Check:
Checked exception needs constructor, throw, and throws declaration [OK]
- Not extending Exception for checked exceptions
- Missing throws declaration in method
- Not calling super(message) in constructor
