C# throw keyword2 min read

We have already discussed the exception handling in C# and how to handle the exception if one exists. The exception discussed are raised by the CLR automatically, now we will see how we can manually raise an exception.

In C#, we use the keyword ‘throw’ in order to throw an exception programmatically. We can raise any type of exception derived from the Exception class with the help of the throw keyword.

The syntax for throw keyword.

throw e;

In this syntax e is an exception that is derived from the Exception class.

Example: C# program for throw keyword

Output:

Employee name is Empty

As you can see new keyword is used to create an object of the exception. Also, a try-catch block is used to handle the exception.

Since the name string is kept empty, the program threw an exception indicating that the name cannot be empty. This is how the throw keyword works in C#.


Re-throwing an Exception

With the use of the catch block and throw keyword, we can re-throw an exception inside the catch block. We pass it to the caller and let them handle it in a way they want.

Example: C# program for re-throwing an exception

Output:

Object reference not set to an instance of an object

As you can see, we throw an exception without any parameters because if we throw an exception with a parameter such as throw e then we will not be able to preserve the stack trace of the original exception.

This is how we Re-throw an exception using throw and catch. Also, if you can go through Exception Handling to learn more on how to handle exceptions.


MORE

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More

Keith Number Program in C++

In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you …
Read More

Singly linked list Program C++

In this tutorial, we will write a C++ program to implement singly linked list. In this program, we will create a separate function for each …
Read More

Fascinating Number Program in C

In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through …
Read More

Peterson Number in C

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C. What is Peterson Number? …
Read More

Peterson Number in C++

In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number …
Read More