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

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More

Inverted Half Pyramid Pattern of Alphabets in C

In this tutorial, we will write a C program to print half Pyramid using alphabets/characters. Before that, you may go through the following topic in …
Read More