Custom exception classes in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
custom exception class in C#?Solution
Step 1: Understand the purpose of exceptions
Exceptions represent errors or unexpected situations in a program.Step 2: Identify why custom exceptions are used
Custom exceptions help describe specific problems clearly, making error handling easier and more meaningful.Final Answer:
To represent specific error conditions clearly in your program -> Option DQuick Check:
Custom exceptions clarify errors = A [OK]
- Thinking custom exceptions improve speed
- Believing they remove need for try-catch
- Assuming they fix errors automatically
MyException in C#?Solution
Step 1: Check inheritance from Exception
Custom exceptions must inherit fromExceptionto behave like exceptions.Step 2: Verify constructor calls base constructor
The constructor should callbase(message)to pass the error message properly.Final Answer:
class MyException : Exception { public MyException(string message) : base(message) {} } -> Option AQuick Check:
Inherit Exception + call base constructor = A [OK]
- Not inheriting from Exception
- Using wrong base class like int
- Defining constructor as void method
class MyException : Exception { public MyException(string message) : base(message) {} }
try {
throw new MyException("Error happened");
} catch (MyException ex) {
Console.WriteLine(ex.Message);
}Solution
Step 1: Understand the throw statement
The code throws aMyExceptionwith message "Error happened".Step 2: Catch block prints exception message
The catch block catchesMyExceptionand printsex.Message, which is "Error happened".Final Answer:
Error happened -> Option BQuick Check:
Throw and catch prints message = C [OK]
- Expecting class name instead of message
- Thinking catch block won't run
- Assuming no output from exception
class MyError : Exception {
public MyError(string msg) {
base(msg);
}
}Solution
Step 1: Check constructor syntax for base call
In C#, calling the base class constructor must be done with a colon after the constructor signature, not inside the body.Step 2: Identify correct syntax
The correct syntax ispublic MyError(string msg) : base(msg) {}, not callingbase(msg);inside the constructor body.Final Answer:
The constructor should call base(msg) using a colon, not inside the body -> Option CQuick Check:
Base constructor call uses colon syntax = B [OK]
- Calling base constructor inside body instead of colon
- Not inheriting from Exception
- Misnaming constructor
InvalidAgeException that should be thrown when a user's age is less than 0 or greater than 120. Which of the following code snippets correctly defines and uses this exception?Solution
Step 1: Verify custom exception class definition
The class inherits fromExceptionand has a constructor callingbase(msg)to pass the message.Step 2: Check usage in method
The method throws the exception with a message when age is invalid, which matches the requirement.Final Answer:
Correct class inheritance, constructor, and usage with message -> Option AQuick Check:
Inherit Exception + throw with message = D [OK]
- Not inheriting from Exception
- Defining constructor as void method
- Missing message in exception constructor
