Though many people don't pay much attention to these two common terms being used in exception handling, in interviews, interviewers frequently ask this difference. So let's see the difference between the two.
Let's write the code that is responsible for producing an exception and we will look at the stack trace produced during exception handling.
We will be implementing the code using "throw" first. Please pay attention to Method2 of Class2.
- namespace ExceptionHandlingSample
- {
- class Program
- {
- static void Main(string[] args)
- {
- Class1 cls1 = new Class1();
- Console.WriteLine(cls1.Method1());
- Console.Read();
- }
- }
-
- class Class1
- {
- public String Method1()
- {
- try
- {
- Class2 cls2 = new Class2();
- return cls2.Method2();
- }
- catch (Exception ex)
- {
- Console.WriteLine("-----Stack Trace for the Exception Occurred------");
- Console.WriteLine(ex.StackTrace.ToString());
- Console.WriteLine("-------Method in which Exception Occurred------");
- Console.WriteLine(ex.TargetSite.ToString());
- }
- return "";
- }
- }
-
- class Class2
- {
- public String Method2()
- {
- try
- {
- FaultyMethod2();
- return "Method2 called";
- }
- catch(Exception ex) {
- throw;
- }
- }
-
- public void FaultyMethod2()
- {
- throw new TimeoutException();
- }
- }
- }
So, in the preceding code we have a main method that calls the Method1 of Class1 using the object cls1.
In Method1, we call Method2 of Class2 using object cls2 that further calls FaultyMethod2 that produces the timeout exception.
The output of the preceding code is as follows:
As we can see in the stack trace, we have a full hierarchy, in other words FaultyMethod2, then Method2 and then Method1 along with the line numbers at which an exception occurred or was thrown. Also, the target site is given as "FaultyMethod2".
Now let's change the "throw" to "throw ex" in Method2 and see the difference. For making this change, replace the catch block in Method2 with the following:
- catch(Exception ex) {
- throw ex;
- }
Now after running the program, the output will change to:
Now please notice that in the stack trace, we see hierarchy as Method2, then Method1 along with the line numbers at which an exception is thrown. Also, the target site is given as "Method2".
Thus, after looking at the output of the "throw" and "throw ex" we can say "throw" maintains the full hierarchy in the stack trace and gives complete information about the exception occurred in the code. Whereas "throw ex" pretends that exceptions occurred on the line where "throw ex" was written and removes all the hierarchy above the method containing the "throw ex" expression.
I hope this article helped you in understanding the difference between "throw" and "throw ex".
Happy coding.