Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Custom exception classes in C Sharp (C#) - Step-by-Step Execution

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
Concept Flow - Custom exception classes
Define class inheriting Exception
Add constructors or properties
Throw custom exception
Catch custom exception
Handle or display error message
End
Create a new exception type by inheriting from Exception, then throw and catch it like built-in exceptions.
Execution Sample
C Sharp (C#)
class MyException : Exception {
  public MyException(string message) : base(message) {}
}

throw new MyException("Oops!");
Defines a custom exception class and throws it with a message.
Execution Table
StepActionEvaluationResult
1Define class MyException inheriting ExceptionClass createdMyException ready to use
2Create new MyException with message "Oops!"Calls constructorException object with message "Oops!"
3Throw MyExceptionException thrownProgram looks for catch block
4Catch MyExceptionCatch block matches typeException caught and handled
5Display exception messageAccess Message propertyOutput: "Oops!"
💡 Exception caught and handled, program continues or ends gracefully
Variable Tracker
VariableStartAfter Step 2After Step 3Final
exceptionInstancenullMyException("Oops!")ThrownCaught and message accessed
Key Moments - 3 Insights
Why do we inherit from Exception to create a custom exception?
Because inheriting Exception lets our class behave like a real exception, so it can be thrown and caught as shown in execution_table step 1 and 3.
What happens if we throw the custom exception but don't catch it?
The program will crash or stop with an error because no catch block handles it, unlike step 4 where the exception is caught.
How do we pass a message to the custom exception?
We pass the message string to the constructor when creating the exception instance, as in step 2, which stores it for later use.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after step 2?
AException thrown
BException object with message "Oops!"
CClass created
DException caught and handled
💡 Hint
Check the 'Result' column for step 2 in execution_table
At which step does the program catch the custom exception?
AStep 4
BStep 1
CStep 3
DStep 5
💡 Hint
Look for the 'Catch MyException' action in execution_table
If we do not inherit from Exception, what would happen when throwing the custom class?
AIt would throw normally
BIt would not be caught by catch blocks for Exception
CIt would cause a compile error
DIt would print the message automatically
💡 Hint
Custom exceptions must inherit Exception to be caught as exceptions (see concept_flow)
Concept Snapshot
Create a custom exception by inheriting Exception class.
Add constructors to pass messages.
Throw with 'throw new YourException()'.
Catch with 'catch (YourException e){}'.
Use Message property to show error info.
Full Transcript
This example shows how to create a custom exception class in C# by inheriting from the Exception base class. First, we define the class with a constructor that accepts a message string. Then, we create an instance of this custom exception and throw it. The program looks for a matching catch block to handle the exception. When caught, we can access the message property to display the error. This process allows us to create meaningful, specific errors for our programs that behave like built-in exceptions.

Practice

(1/5)
1. What is the main reason to create a custom exception class in C#?
easy
A. To automatically fix errors when they occur
B. To make the program run faster
C. To avoid using try-catch blocks
D. To represent specific error conditions clearly in your program

Solution

  1. Step 1: Understand the purpose of exceptions

    Exceptions represent errors or unexpected situations in a program.
  2. Step 2: Identify why custom exceptions are used

    Custom exceptions help describe specific problems clearly, making error handling easier and more meaningful.
  3. Final Answer:

    To represent specific error conditions clearly in your program -> Option D
  4. Quick Check:

    Custom exceptions clarify errors = A [OK]
Hint: Custom exceptions explain specific errors clearly [OK]
Common Mistakes:
  • Thinking custom exceptions improve speed
  • Believing they remove need for try-catch
  • Assuming they fix errors automatically
2. Which of the following is the correct way to declare a custom exception class named MyException in C#?
easy
A. class MyException : Exception { public MyException(string message) : base(message) {} }
B. class MyException { public MyException(string message) {} }
C. class MyException : int { public MyException(string message) : base(message) {} }
D. class MyException : Exception { public void MyException(string message) {} }

Solution

  1. Step 1: Check inheritance from Exception

    Custom exceptions must inherit from Exception to behave like exceptions.
  2. Step 2: Verify constructor calls base constructor

    The constructor should call base(message) to pass the error message properly.
  3. Final Answer:

    class MyException : Exception { public MyException(string message) : base(message) {} } -> Option A
  4. Quick Check:

    Inherit Exception + call base constructor = A [OK]
Hint: Inherit Exception and call base constructor for message [OK]
Common Mistakes:
  • Not inheriting from Exception
  • Using wrong base class like int
  • Defining constructor as void method
3. What will be the output of the following C# code?
class MyException : Exception { public MyException(string message) : base(message) {} }
try {
throw new MyException("Error happened");
} catch (MyException ex) {
Console.WriteLine(ex.Message);
}
medium
A. Exception caught
B. Error happened
C. MyException
D. No output

Solution

  1. Step 1: Understand the throw statement

    The code throws a MyException with message "Error happened".
  2. Step 2: Catch block prints exception message

    The catch block catches MyException and prints ex.Message, which is "Error happened".
  3. Final Answer:

    Error happened -> Option B
  4. Quick Check:

    Throw and catch prints message = C [OK]
Hint: Catch prints exception message property [OK]
Common Mistakes:
  • Expecting class name instead of message
  • Thinking catch block won't run
  • Assuming no output from exception
4. Identify the error in this custom exception class declaration:
class MyError : Exception {
public MyError(string msg) {
base(msg);
}
}
medium
A. The class must not inherit from Exception
B. The constructor should be named differently from the class
C. The constructor should call base(msg) using a colon, not inside the body
D. The base class Exception does not accept a string parameter

Solution

  1. 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.
  2. Step 2: Identify correct syntax

    The correct syntax is public MyError(string msg) : base(msg) {}, not calling base(msg); inside the constructor body.
  3. Final Answer:

    The constructor should call base(msg) using a colon, not inside the body -> Option C
  4. Quick Check:

    Base constructor call uses colon syntax = B [OK]
Hint: Call base constructor with colon, not inside method body [OK]
Common Mistakes:
  • Calling base constructor inside body instead of colon
  • Not inheriting from Exception
  • Misnaming constructor
5. You want to create a custom exception 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?
hard
A. class InvalidAgeException : Exception { public InvalidAgeException(string msg) : base(msg) {} }
void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException("Age is invalid"); }
B. class InvalidAgeException { public InvalidAgeException(string msg) {} }
void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException("Age is invalid"); }
C. class InvalidAgeException : Exception { public void InvalidAgeException(string msg) {} }
void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException("Age is invalid"); }
D. class InvalidAgeException : Exception { public InvalidAgeException() {} }
void CheckAge(int age) { if(age < 0 || age > 120) throw new InvalidAgeException(); }

Solution

  1. Step 1: Verify custom exception class definition

    The class inherits from Exception and has a constructor calling base(msg) to pass the message.
  2. Step 2: Check usage in method

    The method throws the exception with a message when age is invalid, which matches the requirement.
  3. Final Answer:

    Correct class inheritance, constructor, and usage with message -> Option A
  4. Quick Check:

    Inherit Exception + throw with message = D [OK]
Hint: Inherit Exception, add constructor, throw with message [OK]
Common Mistakes:
  • Not inheriting from Exception
  • Defining constructor as void method
  • Missing message in exception constructor