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

Java Program to find the sum of the Largest Forward Diagonal

in this tutorial, we will write a java program to find the sum of the Largest Forward Diagonal in an Arraylist (matrix). Java Program to …

C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a number using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …