473,378 Members | 1,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Rethrowing an exception and preserving stack trace

If I got the following code:

try
{
// something that might throw an exception
}
catch (Exception ex)
{
// Log contents of ex here
throw;
}

this will rethrow the exception after logging it, however the stack
trace from there on will show the line of the "throw;" statement as the
first entry. If I drop the try/catch block here then the actual line of
code throwing the exception will be the first entry.

Using either "throw;" or "throw ex;" produces the same result, the
existing stack trace gets replaced with a new one starting with the
re-throwing statement.

Is there a way to fix this? Can I do something that will keep the
existing stack trace? Wether the re-throwing statement line and file
gets added to the stack trace or not is not important, I just don't want
to loose the history from the stack trace to that point.

Throwing a new exception and using the previous one as an InnerException
does not change it as only the new exceptions stack trace is reset,
however it seems a bit awkward to do this all over:

throw new SomeExceptionHere(ex.Message, ex);

just to keep the stack trace, and of course I would have to unwind the
tree of exceptions later on to rebuild the full stack trace anyway.

--
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2
Jan 17 '06 #1
2 4359

Lasse Vågsæther Karlsen wrote:
If I got the following code:

try
{
// something that might throw an exception
}
catch (Exception ex)
{
// Log contents of ex here
throw;
}

this will rethrow the exception after logging it, however the stack
trace from there on will show the line of the "throw;" statement as the
first entry. If I drop the try/catch block here then the actual line of
code throwing the exception will be the first entry.

Using either "throw;" or "throw ex;" produces the same result, the
existing stack trace gets replaced with a new one starting with the
re-throwing statement.


No - using throw; should be okay, but using throw ex; replaces the
stack trace.

Here's an example:

using System;
using System.Runtime.CompilerServices;

class Test
{
[MethodImpl(MethodImplOptions.NoInlining)]
static void InnerCall()
{
throw new Exception();
}

[MethodImpl(MethodImplOptions.NoInlining)]
static void OuterCall()
{
try
{
InnerCall();
}
catch
{
throw;
}
}
static void Main()
{
try
{
OuterCall();
}
catch (Exception e)
{
Console.WriteLine (e);
}
}
}

Output is:
System.Exception: Exception of type 'System.Exception' was thrown.
at Test.InnerCall()
at Test.OuterCall()
at Test.Main()

Changing the "throw;" to "throw ex;" (declaring the exception of
course) changes the output to:

System.Exception: Exception of type 'System.Exception' was thrown.
at Test.OuterCall()
at Test.Main()

I've included some attributes to ensure the JIT doesn't inline things.
They don't appear to make a difference in this case, but inlining may
explain why you've seen it not work in the past.

Jon

Jan 17 '06 #2
Jon Skeet [C# MVP] wrote:
Lasse Vågsæther Karlsen wrote:

<snip>
this will rethrow the exception after logging it, however the stack
trace from there on will show the line of the "throw;" statement as the
first entry. If I drop the try/catch block here then the actual line of
code throwing the exception will be the first entry.


<snip>
Changing the "throw;" to "throw ex;" (declaring the exception of
course) changes the output to:

System.Exception: Exception of type 'System.Exception' was thrown.
at Test.OuterCall()
at Test.Main()

I've included some attributes to ensure the JIT doesn't inline things.
They don't appear to make a difference in this case, but inlining may
explain why you've seen it not work in the past.

Jon


Thanks, I notice the same when I add the attributes, so then I know what
it is.
--
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2
Jan 18 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Chris Herring | last post by:
Hi there: Well, let me start off by saying that I am a Visual Studio drag and drop weenie, not a real programmer. So I tend to get confused when things do not look like the instructions said they...
0
by: Mike Schilling | last post by:
I have some code that calls methods reflectively (the method called and its parameters are determined by text received in a SOAP message, and I construct a map from strings to MethodInfos). The...
4
by: Barry Mossman | last post by:
Hi, I am throwing an exception derived from ApplicationException as follows catch (Exception ex) { throw new MyException("message", ex); } My exception's constructor is: public...
2
by: Chris Stiefeling | last post by:
Hi, I am experiencing a strange problem. I am reading and writing xml files via XmlDocument and XmlTextWriter. In the debugger everything works fine but outside the debugger (debug or release)...
5
by: Steven T. Hatton | last post by:
I haven't thought about rethrowing an exception in a long time, and tried to do it the wrong way. Now I'm curious about /why/ it's wrong. My expectation was that the exception instance would...
15
by: =?Utf-8?B?TWljaGVsIFBvc3NldGggW01DUF0=?= | last post by:
In my opinion rethrowing exceptions without providing anny extra information is a totall waste Examples : in my opinion wrong : A: Public sub DoSomeStuff() Try do it
4
by: Coder Guy | last post by:
I am implementing an asynchronous handler (similar to Control.EndInvoke) and if the other thread throws an exception, I catch it and rethrow it on the current thread. How can I rethrow the...
13
by: valentin tihomirov | last post by:
I do not understand something. A caught exception stack points to an argument-free 'throw' in a catch block. Meantime, it is widely known that these statements re-throw the original exceptions. I...
2
by: Scott | last post by:
I'm debugging an xmlrpc client/server application. Often when an exception occurs in the server, I receive only a very short error message on the client. For example: xmlrpclib.Fault: <Fault 1:...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.