Handle Exception carefully means I am not going to discuss some rocket science about exception handling but I am going to discuss how not to shadow the exception in your program. I am not going to discuss more. I am starting my example.
class Program
{
static void Main(string[] args)
{
try
{
Program p = new Program();
p.MethodA();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
public void MethodA()
{
try
{
MethodB();
}
catch (Exception ex)
{
throw ex;
}
}
public void MethodB()
{
try
{
MethodC();
}
catch (Exception ex)
{
throw ex;
}
}
public void MethodC()
{
int a = 10;
int b = 0;
int c = 0;
try
{
c = a / b;
}
catch (Exception ex)
{
throw ex;
}
}
}
When executing the program, you will get the following output as result. Yes, you will be able to handle the exception thrown by the method and displayed on the console.
Output

But the actual thing is you are hiding the stack trace and each time you throw the exception by writing throw ex
, you are creating a new stack trace. So you are not able to get the actual path from where the exception gets thrown.
Now to understand the thing properly, write the program again and now replace throw ex
by the throw
:
class Program
{
static void Main(string[] args)
{
try
{
Program p = new Program();
p.MethodA();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
public void MethodA()
{
try
{
MethodB();
}
catch
{
throw;
}
}
public void MethodB()
{
try
{
MethodC();
}
catch
{
throw;
}
}
public void MethodC()
{
int a = 10;
int b = 0;
int c = 0;
try
{
c = a / b;
}
catch
{
throw;
}
}
}
When executing the program, you will get the following output:
Output

Now as you see when you replace the line, there is no new stacktrace that gets created and you get the actual path from where exception gets thrown.
Summary
So make use of throw
to get the actual path of the exception rather than using throw ex
.
CodeProject