Custom exception classes in C Sharp (C#) - Time & Space Complexity
When we create custom exception classes, we want to know how much extra work the program does when it throws or handles these exceptions.
We ask: How does the time to create and use a custom exception grow as the program runs?
Analyze the time complexity of the following code snippet.
public class MyCustomException : Exception
{
public MyCustomException(string message) : base(message) {}
}
void Process(int n)
{
for (int i = 0; i < n; i++)
{
if (i == 5) throw new MyCustomException("Error at 5");
}
}
This code defines a custom exception and throws it inside a loop when a condition is met.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 0 to n-1.
- How many times: Up to n times, but the exception stops the loop early at i = 5.
As n grows, the loop runs more times until it hits the exception condition.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 6 (loop stops at i=5) |
| 100 | 6 (loop stops at i=5) |
| 1000 | 6 (loop stops at i=5) |
Pattern observation: The loop stops early, so operations stay about the same regardless of n.
Time Complexity: O(1)
This means the time to throw the custom exception does not grow with input size because it happens at a fixed point.
[X] Wrong: "Creating a custom exception always makes the program slower as input grows."
[OK] Correct: The exception is thrown at a specific point, so the time to create it does not depend on input size.
Understanding how exceptions affect program speed helps you write clear and efficient error handling, a useful skill in real projects and interviews.
"What if the exception was thrown inside a nested loop that runs n times inside another n times? How would the time complexity change?"