473,839 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bug?! throw vs. throw ex

I want to "rethrow" an exception so as not to lose the original stack
trace information. I understood that I could use throw, like:

try {
DoIt();
}
catch (Exception ex) {
DoSomeException Stuff(ex);
throw;
}
However, this apparently does NOT preserve the stack trace--it loses it
just like using throw ex; does! I am currently using .NET 1.1 SP1. Is
this a known bug? Why do so many people report that it works for them?
Have they actually tried it?

Why would a bug like this exist in v. 1.1 SP1?
Can anyone help shed some light on this?

Thanks in advance.

Nov 16 '05 #1
12 4329
the rethrow does not preserve the stack. it is not a bug. You need preserve
the stack and then throw a new exception with the amended stack

--
Regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://tinyurl.com/27cok
----------------------------------------------------------
"GoogleNewsRead erMan" <lo***********@ hotmail.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
I want to "rethrow" an exception so as not to lose the original stack
trace information. I understood that I could use throw, like:

try {
DoIt();
}
catch (Exception ex) {
DoSomeException Stuff(ex);
throw;
}
However, this apparently does NOT preserve the stack trace--it loses it
just like using throw ex; does! I am currently using .NET 1.1 SP1. Is
this a known bug? Why do so many people report that it works for them?
Have they actually tried it?

Why would a bug like this exist in v. 1.1 SP1?
Can anyone help shed some light on this?

Thanks in advance.

Nov 16 '05 #2
> I want to "rethrow" an exception so as not to lose the original stack
trace information.


I believe the stack trace is populated as part of the throw, not when the
exception object is created.

Create a new exception and stuff the old one inside it as the "inner
exception". The new one should have the new stack trace and the old one the
original stack trace.
Nov 16 '05 #3
Not sure if it works, but try

throw new Exception("some message", ex)

"GoogleNewsRead erMan" <lo***********@ hotmail.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
I want to "rethrow" an exception so as not to lose the original stack
trace information. I understood that I could use throw, like:

try {
DoIt();
}
catch (Exception ex) {
DoSomeException Stuff(ex);
throw;
}
However, this apparently does NOT preserve the stack trace--it loses it
just like using throw ex; does! I am currently using .NET 1.1 SP1. Is
this a known bug? Why do so many people report that it works for them?
Have they actually tried it?

Why would a bug like this exist in v. 1.1 SP1?
Can anyone help shed some light on this?

Thanks in advance.

Nov 16 '05 #4
Yes, it's a bug. It is supposed to be fixed in Whidbey. For now you will
need to wrap the exception in a new exception object and use the original
exception as the inner exception.

"GoogleNewsRead erMan" <lo***********@ hotmail.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
I want to "rethrow" an exception so as not to lose the original stack
trace information. I understood that I could use throw, like:

try {
DoIt();
}
catch (Exception ex) {
DoSomeException Stuff(ex);
throw;
}
However, this apparently does NOT preserve the stack trace--it loses it
just like using throw ex; does! I am currently using .NET 1.1 SP1. Is
this a known bug? Why do so many people report that it works for them?
Have they actually tried it?

Why would a bug like this exist in v. 1.1 SP1?
Can anyone help shed some light on this?

Thanks in advance.

Nov 16 '05 #5
<"Alvin Bruney [MVP]" <vapor at steaming post office>> wrote:
the rethrow does not preserve the stack. it is not a bug. You need preserve
the stack and then throw a new exception with the amended stack


Not true. Try this:

using System;

class Test
{
static void Main()
{
try
{
DoSomething();
}
catch (Exception e)
{
Console.WriteLi ne (e);
}
}

static void DoSomething()
{
try
{
DoSomethingNaug hty();
}
catch (Exception)
{
throw;
}
}

static void DoSomethingNaug hty()
{
string x = null;
bool y = x.Equals("hello ");
}
}

Compile it with debug turned on and run it. I get a stack trace of:
System.NullRefe renceException: Object reference not set to an instance
of an object.
at Test.DoSomethin gNaughty() in c:\test\Test.cs :line 32
at Test.DoSomethin g() in c:\test\Test.cs :line 25
at Test.Main() in c:\test\Test.cs :line 9

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
Jako Menkveld wrote:
Not sure if it works, but try

throw new Exception("some message", ex)


That would give you a new exception, with this place as stack-trace and
the old exception (with the old stack-trace) as it's "Inner" exception.

I have come to almost loathe the above way of coding, since it means
that catchers cannot use the type of the exception to dispatch to a
catch-handler but has to catch Exception and to analysis on the content
of e.Inner.

This is especially interesting with Delegate, which throws a wrapped
exception if invoking the Delegate throws an exception (/me holds back a
swarm of swearwords).

The difference between "throw e;" and "throw;" is that "throw;" rethrows
the original catch'ed exception unchanged (like in C++) whereas "throw
e"; throws the expression e, which happens to refer to a catch'ed
exception object.

--
Helge
Nov 16 '05 #7
I get the same results as you. I stand corrected.

--
Regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://tinyurl.com/27cok
----------------------------------------------------------
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"Alvin Bruney [MVP]" <vapor at steaming post office>> wrote:
the rethrow does not preserve the stack. it is not a bug. You need
preserve
the stack and then throw a new exception with the amended stack


Not true. Try this:

using System;

class Test
{
static void Main()
{
try
{
DoSomething();
}
catch (Exception e)
{
Console.WriteLi ne (e);
}
}

static void DoSomething()
{
try
{
DoSomethingNaug hty();
}
catch (Exception)
{
throw;
}
}

static void DoSomethingNaug hty()
{
string x = null;
bool y = x.Equals("hello ");
}
}

Compile it with debug turned on and run it. I get a stack trace of:
System.NullRefe renceException: Object reference not set to an instance
of an object.
at Test.DoSomethin gNaughty() in c:\test\Test.cs :line 32
at Test.DoSomethin g() in c:\test\Test.cs :line 25
at Test.Main() in c:\test\Test.cs :line 9

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #8
One arguable flaw here, though, is that you lose the location within
the DoSomething() method --- the line number is that of the throw. So,
in fact, the stack trace is modified, and not that of the original
exception.
Jon wrote:
<"Alvin Bruney [MVP]" <vapor at steaming post office>> wrote:
the rethrow does not preserve the stack. it is not a bug. You need preserve the stack and then throw a new exception with the amended stack
Not true. Try this:

using System;

class Test
{
static void Main()
{
try
{
DoSomething();
}
catch (Exception e)
{
Console.WriteLi ne (e);
}
}

static void DoSomething()
{
try
{
DoSomethingNaug hty();
}
catch (Exception)
{
throw;
}
}

static void DoSomethingNaug hty()
{
string x = null;
bool y = x.Equals("hello ");
}
}

Compile it with debug turned on and run it. I get a stack trace of:
System.NullRefe renceException: Object reference not set to an

instance of an object.
at Test.DoSomethin gNaughty() in c:\test\Test.cs :line 32
at Test.DoSomethin g() in c:\test\Test.cs :line 25
at Test.Main() in c:\test\Test.cs :line 9

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Nov 16 '05 #9
Gentlemen,

There seem to be a lot of experts replying to this thread so I will add
my own question. If you wanted to get the same exception at a higher
level, why would you catch it at all?

for example (modifying the previous code):

using System;

class Test
{
static void Main()
{
try
{
DoSomething();
}
//handle all exceptions without bias on moral behavior
catch (Exception e)
{
Console.WriteLi ne (e);
}
}

static void DoSomething()
{
try
{
DoSomethingNaug hty();
}
catch (NaughtyExcepti on)
{
//handle the offending problem
}
//let all of the less ethicly challenged exceptions bubble up
the the calling Main()
}

static void DoSomethingNaug hty()
{
string x = null;
bool y = x.Equals("hello ");
}
}

If I wanted to do some intermediate processing in the routine and then
still post an error to the calling method, I would throw a new
exception (of whatever type) with the original exception as the inner
exception. Does stuffing the old exception into the new still mess up
the stack?

Thanks,
Dan

Nov 16 '05 #10

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

Similar topics

8
1763
by: Christian Schuhegger | last post by:
hi, we are working on a c++ project which has a lot of thow list specifications which in the end causes a lot of problems. now i would like to remove them from the project. because the project has a size of 300000+ lines of code it is not so easy to do all of that manually. therefore my question: is there a tool that you run on your sources and which just converts the throw declarations into a comment? a tool that only comments the...
3
3511
by: Pierre Rouleau | last post by:
The std::exception class defined in the Standard C++ <exception> header specifies that the constructors could throw any exception becuase they do not have a throw() specification. Why is that? Is this because there could be an exception thrown when the code creates a std::exception? I would assume that is not the case. However, if I want to create a new exception class, derived from std::exception (say MyException) then how can I...
1
1628
by: Rennie deGraaf | last post by:
I want to use throw() specifiers on some of my methods while debugging, to help me keep track of what is going on, but remove them in release builds. My method of doing this is #ifdef DEBUG #define THROW(...) throw (__VA_ARGS__) #else #define THROW(...) #endif
9
2695
by: wij | last post by:
Hi: In recent pondering, I am begining suspecting the usefulness of throw specification in the language(I know this opinion have long existed), even for delete!. The primary reason is that reimplementing such members or functions cannot throw any types other than specified (what would be the justifiable reason? Besides, stack unwinding may be initiated by NPTL implemented cancellation with unspecified throw type and compiler may enable...
3
2361
by: Nenad Dobrilovic | last post by:
Hi, I have function which is throwning exception, like this: public class LoggedException : Exception { public void Throw() { throw this; } }
6
5723
by: Arjen | last post by:
Hi, I'm reading the enterprise library documentation and there I see the throw statement. try { // run code } catch(Exception ex) {
18
3238
by: Ranganath | last post by:
Why is throw keyword considered as an operator?
28
3817
by: gnuist006 | last post by:
I have some code like this: (if (test) (exit) (do something)) or (if (test)
2
1065
by: =?Utf-8?B?UHVyZSBIZWFydA==?= | last post by:
Hi for me the throw statment is very confusing and un clear, i mean for structured error handeling if the eception is not handeled it will search for handlers in the calling methods hirarchy so why we need to re throw the exception to the calling method since it will be done autimatically by .NET ? whats the use of throw then ? thank you
6
1965
by: jason.cipriani | last post by:
Consider this program, which defines a template class who's template parameter is the type of an exception that can be thrown by members of the class: === BEGIN EXAMPLE === #include <iostream> #include <string> using namespace std;
0
9698
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,...
1
10654
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
10297
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
9426
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
7833
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
7021
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5683
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...
1
4493
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3136
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.