Throw and throw ex both are used to throw exception caught
in catch block.
Throw: It preserve the stack trace.
Example: Method1
throw Error1 and caught by Method2 and again this method throws Error2
StackTrace:
Method1 Error1 + Method2Error2
using System;
using
System.Collections.Generic;
{
class Program
{
static void Main(string[] args)
{
try
{
DevideNumberByZero(100);
}
catch (Exception ex)
{
throw;
}
}
{
try
{
Devide(num);
}
catch (Exception)
{
}
}
public static void Devide( int num)
{
try
{
int d = 0;
int res = num / d;
Console.WriteLine(res);
}
catch (Exception)
{
throw;
}
}
}
}
Output:
Throw Ex: It does not preserve stack trace, so it
will clear stack trace and will return only Method2Error2
Example: Method1 throw Error1 and caught by
Method2 and again this method throws Error2.
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
try
{
DevideNumberByZero(100);
}
catch (Exception ex)
{
throw ex;
}
}
public static void DevideNumberByZero(int num)
{
try
{
Devide(num);
}
catch (Exception ex)
{
throw ex;
}
}
public static void Devide( int num)
{
try
{
int d = 0;
int res = num / d;
Console.WriteLine(res);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Output:
No comments:
Post a Comment