#47: throwing Exception

you can throw exception in two ways.

1.throw. This will throw the caught exception.The throwed exception must be caught again.It will not reset the stack trace.

2.throw e or throw new CustomException : It behaves exactly same but it will reset the stack trace.

Experimentation of Throw vs Throw ex(throw new CustomException):

DivByZero Method:

private static void DivByZero()
 {
 int j = 0;
 var result = 9/j; //Line No :45 in my program is the  Cause of Exception
 }

1.Throw:It does not  reset the stack trace,instead preserves it and throws the exception

private static void thrwonigException(){
 try
 {
 DivByZero();
 }catch (DivideByZeroException e)
 {
 /*It will not reset stack trace,instead throws the caught exception */.
 throw ;
 }
}

It still maintains the line which causes the exception,

throw

2.Throw e : Returns the line no 34 as cause of exception but not 45,the stack trace is reset after this line

private static void thrwonigException(){
try
 {
 DivByZero();
 }
 catch (DivideByZeroException e)
 {
 /*It will reset the stack trace and tells that this line is the cause of exception.
 * It will not who caused the exception.
 * */
 throw e; //or throw new DivideByZeroException();
 }
}

Throw Ex

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s