473,734 Members | 2,724 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"try{throw}catc h"

in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?

Nov 15 '06 #1
7 2421
* dick:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?
Short answer: Magic.

Almost-short answer: the dynamic type of the object throw by 'throw' is
known statically, and is the same as the static type because objects are
thrown by value, and the static type of object caught by 'catch' is
known statically, and is the only thing that matters for whether a
'catch' clause will catch. The linker has access to all this
information. And so it can arrange the necessary tables or global type
identifiers or whatever the implementation is based on (there are two
main ways to do it, but an infinite number of possible ways to do it).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 15 '06 #2

dick wrote:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?
That depends on the function's exception specification.
The function is not "returning" the error, the execution context is
throwing the anomally. Where, if and when the anomally is caught
depends on guarded contexts (try blocks) and their catch blocks.

Thats like asking how does an integer know that its an integer? You
can't do anything in C++ without the type being known. Objects always
know their type or type(s) if inheritance is involved. If you throw a
baseball, the baseball knows its a baseball. If you construct and throw
a std::runtime_er ror, trust me, the object knows that its a
runtime_error. even if you catch( const std::exception& e) - a
reference to its base, the runtime_error still knows its a
runtime_error.

Nov 15 '06 #3

Salt_Peter wrote:
dick wrote:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?

That depends on the function's exception specification.
The function is not "returning" the error, the execution context is
throwing the anomally. Where, if and when the anomally is caught
depends on guarded contexts (try blocks) and their catch blocks.

Thats like asking how does an integer know that its an integer? You
can't do anything in C++ without the type being known. Objects always
know their type or type(s) if inheritance is involved. If you throw a
baseball, the baseball knows its a baseball. If you construct and throw
a std::runtime_er ror, trust me, the object knows that its a
runtime_error. even if you catch( const std::exception& e) - a
reference to its base, the runtime_error still knows its a
runtime_error.


But how the "catch" know the type.

Nov 15 '06 #4

Alf P. Steinbach wrote:
* dick:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?

Short answer: Magic.

Almost-short answer: the dynamic type of the object throw by 'throw' is
known statically, and is the same as the static type because objects are
thrown by value, and the static type of object caught by 'catch' is
known statically, and is the only thing that matters for whether a
'catch' clause will catch. The linker has access to all this
information. And so it can arrange the necessary tables or global type
identifiers or whatever the implementation is based on (there are two
main ways to do it, but an infinite number of possible ways to do it).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
is there any memory leak when a function throw an object?

Nov 15 '06 #5

dick wrote:
Salt_Peter wrote:
dick wrote:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?
That depends on the function's exception specification.
The function is not "returning" the error, the execution context is
throwing the anomally. Where, if and when the anomally is caught
depends on guarded contexts (try blocks) and their catch blocks.

Thats like asking how does an integer know that its an integer? You
can't do anything in C++ without the type being known. Objects always
know their type or type(s) if inheritance is involved. If you throw a
baseball, the baseball knows its a baseball. If you construct and throw
a std::runtime_er ror, trust me, the object knows that its a
runtime_error. even if you catch( const std::exception& e) - a
reference to its base, the runtime_error still knows its a
runtime_error.



But how the "catch" know the type.
The catch does not need to know the type. In fact, if the catch is
catch(...) { }
It will never know the type.
Since catch blocks typically have a specific parameter, anything that
is succesfully "caught" by the parameter is therefore of that type or
derived of that type.

Its really a simple system.

int main()
{
try {
throw std::string("er ror");
{
catch( integer& e ) // can only catch integers
{
}
catch ( std::string& e) // can only catch std::string or derivatives
{
std::cerr << e << std::endl
}
catch( ... )
{
}
}

Its obvious that the thrown object can only initialize the second catch
block's parameter.
Hence, the std::string's type is known.

Nov 15 '06 #6

dick wrote:
Alf P. Steinbach wrote:
* dick:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?
Short answer: Magic.

Almost-short answer: the dynamic type of the object throw by 'throw' is
known statically, and is the same as the static type because objects are
thrown by value, and the static type of object caught by 'catch' is
known statically, and is the only thing that matters for whether a
'catch' clause will catch. The linker has access to all this
information. And so it can arrange the necessary tables or global type
identifiers or whatever the implementation is based on (there are two
main ways to do it, but an infinite number of possible ways to do it).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

is there any memory leak when a function throw an object?
Oh yes there can be. *If* you allocate with new, the compiler is no
longer responsible for that allocation. That does not change when an
exception is thrown.
Obviously, any local objects are automatically destroyed. The same
holds with smart pointers.

You can safely protect yourself:
a) by not using new/delete
b) using smart pointers
c) by having the catch block check for and deallocate any newed
allocations. That - you need to do carefully.

Take for example the code below and lets artificially throw a
bad_allocation exception before delete invokes A's d~tor.

#include <iostream>
#include <stdexcept>

class A
{
};

int main()
{
// pointer must not be in try block
A* p_a = 0; // nullified
try
{
A a; // local
p_a = new A;
std::cout << "p_a = " << p_a << std::endl;
// do stuff and throw for a test
throw std::bad_alloc( ); // or std::runtime_er ror
delete p_a;
std::cout << "end of try block\n";
}
catch( const std::exception& e)
{
std::cerr << "error: ";
std::cerr << e.what() << std::endl;
std::cerr << "p_a = " << p_a << std::endl;
if(p_a)
{
delete p_a;
std::cerr << "*** p_a deleted ***" << std::endl;
}
}
}

/*
p_a = 0x503010
<- "end of try block" was never reached
error: St::bad_alloc <- in catch block
p_a = 0x503010
*** p_a deleted ***
*/

Nov 15 '06 #7

dick wrote:
>
is there any memory leak when a function throw an object?
You have questions about exception safety. Instead of asking them all
you might think about buying the book "Exceptiona l C++", which should
answer many and even ones you never thought to ask.

Nov 15 '06 #8

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

Similar topics

40
3038
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution model (specifically, exceptions). Without fail, when I start talking with some of the "old-timers"...
3
8335
by: lwoods | last post by:
Why isn't my "catch" catching? TIA, Larry Woods This script get's this output:: Warning: Division by zero in C:\Inetpub\wwwroot\PHP\tests.php on line 4 This will never be printed
5
17276
by: Jesee | last post by:
I am reading Jeffrey Richter's book "Applied Microsoft .NET Framework programming",i came across "Exception handing". Page 405 says "If the stack overflow occurs within the CLR itself,your application code won't be able to catch the StackOverflowException exception and none of your finally blocks will excute.",I don't understand it. Following C# statement: class App { static void Main() {
6
1675
by: Chris Newcombe | last post by:
Please could someone on the VC++ 7.0 compiler team (note; not 7.1) tell me if this code is handled 'correctly' (i.e. as the original poster suggests) in all cases? http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=89ed5u%248ck%40library1.airnews.net (Incase the URL doesn't make it I've copied it below.) I have a situation where I really need this technique. But the fact that Dave Abrahams wasn't sure about it very much worries...
20
3621
by: DraguVaso | last post by:
Hi, As a former VB-programmer I'm used to the "on error goto"-errorhandling. I see that in actually all the VB.NET-samples I can fin people use the "Try - catch"-errorhandling. Which of the two is the best? Are there good reasons to use the Try-Catch? Will the "on error goto" disapear in the future? Are there any logical reasons to use trey-catch? Is it 'better' programming? etc etc :-)
15
2717
by: bill salkin | last post by:
I'd like to create a custom error handler like this in VB.NET: .... try ... Throw ("Lender Name not in table") .... catch ("Lender Name not in table")
6
4453
by: bill salkin | last post by:
I setup a "Try..." block and attempted to open a non- existant database. It went to the second "catch" not the first. What is the proper "catch" clause for this specific case? TIA, Bill
10
2416
by: pauldepstein | last post by:
I have read about exception handling in a few books and websites but am still confused on a basic point. I understand the try ... catch syntax. However, I have seen examples of using throw where the throw-command is not in a try-block. What is the difference in meaning between throwing in a try block and throwing outside a try block?
6
12004
by: Dave | last post by:
I really don't like the users getting an unhandled expception page, and I'm still to new with ASP.Net and C#. So please accept my appology for the 2 part question. SqlException (0x80131904) 1.) Is an "Cannot insert duplicate key row" exception from a FormView returned as part of the ItemInserting or ItemInserted event? 2.) What is the recommended way to catch and deal with an "Cannot
0
8946
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
8776
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
9449
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...
0
8186
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
6735
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
6031
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
4550
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
3261
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
2180
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.