In c#, the throw is a keyword, and it is useful to throw an exception manually during the execution of the program, and we can handle those thrown exceptions using try-catch blocks based on our requirements.
throw keyword will raise only the exceptions that are derived from the
Exception base class.
Following is the syntax of raising an exception using
throw keyword in c#.
Here, e is an exception that is derived from the
Exception class and
throw keyword to throw an exception.
Following is the example of using
throw keyword to throw NullReferenceException and handling thrown exceptions in a try-catch block in c#.
If you observe the above example, the GetDetails() method will throw NullReferenceException using the throw keyword whenever the name variable value is empty or null.
Here, we used a
new keyword in
throw statement to create an object of valid exception type, and we used a try-catch block in method caller to handle thrown exception.
When we execute the above example, we will get the result as shown below.
This is how we can throw an exception in c# using
throw keyword based on our requirements.
throw keyword in the
catch block, we can re-throw an exception that is handled in the
catch block. The re-throwing an exception is useful when we want to pass an exception to the caller to handle it in a way they want.
Following is the example of re-throwing an exception to the caller using
throw keyword with try-catch blocks in c#.
If you observe the above example, in GetDetails() method, we used a
throw keyword in the
catch block to re-throw an exception to the caller. In the Main() method, we used a try-catch statement to handle the re-thrown exception.
To re-throw an exception, you need to use
throw keyword without any exception parameter. If we try to re-throw an exception using an exception parameter like
throw e, then the stack trace of the original exception will not be preserved, so if you want to re-throw an exception, then don’t use any exception parameter with
When you execute the above program, you will get the result as shown below.
This is how we can re-throw an exception to the caller using
throw keyword in
catch block based on our requirements.