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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; namespace ExceptionEg { class Employee { static void Main(string[] args) { try { empDetails(); } catch (Exception e) { Console.WriteLine(e.Message); } } // static method private static void empDetails() { string emp_name = null; if (string.IsNullOrEmpty(emp_name)) { throw new NullReferenceException("Employee name is Empty"); } else { Console.WriteLine("Employee Name: " + emp_name); } } } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; namespace ExceptionEg { class Employee { static void Main(string[] args) { try { empDetails(); } catch (Exception e) { Console.WriteLine(e.Message); } } // static method private static void empDetails() { string emp_name = null; try { if (emp_name.Length > 0) { Console.WriteLine("Employee Name: {0}", emp_name); } } catch (Exception e) { throw; } } } } |
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.