C Custom Exceptions
C# errors can be broadly categorized into two types: compile-time errors and run-time errors. The runtime errors are also called exceptions.
The compile-time errors are caught during code compilation while exceptions are caught at runtime.
In this article, you will see what are C# exceptions and how you can create your own custom C# exceptions.
Exceptions Handling in C#
Before you go and create your custom exception. It is pertinent to understand the basic C# exception handling mechanism. C# contains many built-in exception classes for different types of exceptions. All the exception classes in C# inherit from the Exception class.
Let’s see a very simple example of how an exception occurs and how it can be handled.
In the script below you initialize two variables a and b. Next, you divide a by b. Since b contains 0, and you cannot divide a number by zero, you will see an exception as shown in the screenshot that follows:
class Program { static void Main(string[] args) { int a = 15; int b = 0; int result = a / b; Console.WriteLine(result); Console.ReadKey(); } }
If you go to the official Microsoft documentation for the DivideByZeroException class, you will see that it follows the following inheritance path:
Object => Exception => SystemException => ArithmeticException => DivideByZeroException
You can see that the DivideByZeroException class inherits from the Exception class followed by some other classes.
Before you go and create your custom exception, let’s first see how you can handle an exception.
To handle an exception, you need to wrap the code that is likely to throw an error, inside the try block. The code that you want to execute in case an exception occurs is wrapped inside the catch block.
You need to pass the Exception class object to the catch block. Since DivideByZeroException inherits from the Exception class, you can pass the base Exception class variable to catch the DivideByZeroException.
class Program { static void Main(string[] args) { try { int a = 15; int b = 0; int result = a / b; Console.WriteLine(result); } catch(Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); } }
Output:
Creating Custom Exception
In addition to built-in Python exceptions, you can also create your own custom exceptions. There are three steps to creating, throwing, and catching a custom exception.
The first step is to create a class that inherits from the Exception class. Next, you need to override the Message property to display your custom message whenever an exception is thrown.
For instance, in the following script, you create an exception ListLimitException which inherits from the Exception class.
class ListLimitException : Exception { //Overriding the Message property public override string Message { get { return "List Limit Reached: More Items Cannot be Inserted"; } } }
To throw an exception, you can use the “throw” keyword followed by the new object of the exception class. For instance, in the following script, the “ListLimitException” is thrown whenever you add more than 4 items in the list “nums”.
The process of catching a custom exception is similar to catching built-in exceptions. You just have to use the catch block and receive the exception object.
For instance, in the following script, the object of the “ListLimitException” is passed to the catch block which then prints the Message property of the object on the console.
class Program { static void Main(string[] args) { try { List<int> nums = new List<int>(); for (int i = 0; i <= 10; i++) { if (i % 2 == 0) { Console.WriteLine(nums.Count); if (nums.Count > 4) throw new ListLimitException(); nums.Add(i); } } } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); } }
The output below shows that when the number of items in the nums list reaches 5, the “LimitException” is thrown and the corresponding message is displayed on the console.
Output:
Other useful articles:
- TOP-10 Basic C# Interview Questions and Answers
- TOP-10 C# Questions for Advanced Programmers
- 10 Important C# Interview Questions and Answers
- Most Asked C# Interview Q & A
- C# Interview for Beginners
- TOP-10 Advanced C# Interview Questions and Answers
- Introduction to Functions in C#
- C# Jagged Arrays
- C Sharp Interview Questions for 5 Years Experience
- C Sharp Interview Questions for Testers
- C Sharp Questions for 10 Years Experience
- Iteration Statements in C#
- Exception Handling in C#
- C Sharp Methods
- C# Data Types
- C# Vs. C++
- Regular Expressions in C Sharp
- Defining Nested Methods in C Sharp
- C Sharp Dynamic Data Type
- C Custom Exceptions
- How to Generate Random Numbers with C Sharp
- Pass by Value vs Pass by Reference in C Sharp