Link Search Menu Expand Document

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();
}
}

 

C Sharp Custom Values

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:

C Custom Values

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:

Custom Values C Sharp

Other useful articles:


Back to top

© , C Sharp Online — All Rights Reserved - Terms of Use - Privacy Policy