473,756 Members | 2,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 SomeExceptionHe re(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***@vk arlsen.no
PGP KeyID: 0x2A42A1C2
Jan 17 '06 #1
2 4389

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. CompilerService s;

class Test
{
[MethodImpl(Meth odImplOptions.N oInlining)]
static void InnerCall()
{
throw new Exception();
}

[MethodImpl(Meth odImplOptions.N oInlining)]
static void OuterCall()
{
try
{
InnerCall();
}
catch
{
throw;
}
}
static void Main()
{
try
{
OuterCall();
}
catch (Exception e)
{
Console.WriteLi ne (e);
}
}
}

Output is:
System.Exceptio n: Exception of type 'System.Excepti on' 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.Exceptio n: Exception of type 'System.Excepti on' 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.Exceptio n: Exception of type 'System.Excepti on' 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***@vk arlsen.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
58112
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 were going to look :) . Here is my current dilemma: I am having a strange problem with my ASP.NET application. I am building the application using Visual Basic .Net in Visual Studio.NET 2003. Lately, I have frequently been getting the following...
0
3677
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 code that does the call looks roughly like: try { // do reflective call response = method.Invoke(obj, params); }
4
4409
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 ExceptionBase(string aMessage, Exception aInnerException): base(aMessage, aInnerException)
2
2892
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) I receive the following error: "The type initializer for "System.Xml.Schema.Validator" threw an exception." I wrote a small console app that contains the problem -- I've just attached the default class which gets run. Output outside the...
5
2862
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 simply be passed up the call stack as the same object. It would therefore behave polymorphically. Is the behavior shown below compiler-specific? I'm using gcc 4.0.2. In terms of what goes on at runtime, why does the `throw e' act as if I threw a...
15
1898
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
2374
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 exception on the current thread while maintaining the stack trace? The best I've come up with is encapsulating the exception as an inner exception. I would prefer to just rethrow the exception directly -- no need for an inner exception. How does...
13
1896
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 expected, therefore, that the stack points to the original 'throw e' code line.
2
4604
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: "<type 'exceptions.AssertionError'>:"> Presumably this is because xmlrpclib on the server is catching the exception, and only sending the exception name to the client, not the server's stack trace.
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9255
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9819
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7226
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.