473,830 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Implementation of catching by type

Consider the following code:

try
{
// throws exceptions of several types
Foo();
}
catch (out_of_range& ex)
{ }
catch (exception& ex)
{ }

Given that this requires identification of object type at runtime, how
is this implemented -- does it use RTTI? If so, then why is RTTI
attacked for its overheads given that any exception-based error
handling strategy would involve it. (I know RTTI can also point to poor
design, ignore that.)
If not, then how is this achieved?

TIA,
--rob

Jan 3 '07 #1
5 1303
[rob desbois] wrote:
Consider the following code:

try
{
// throws exceptions of several types
Foo();
}
catch (out_of_range& ex)
{ }
catch (exception& ex)
{ }

Given that this requires identification of object type at runtime, how
is this implemented -- does it use RTTI?
Exactly.
If so, then why is RTTI
attacked for its overheads given that any exception-based error
handling strategy would involve it. (I know RTTI can also point to poor
design, ignore that.)
I don't think RTTI is evil per se, it has overhead (tiny, usually in the
form of some bytes for each polymorphic class instantiated) but so far I've
seen almost NO correct explicit RTTI usage other one exception: when I had
to implement a serialization framework to work with polymorphic types (ex.
when deserializing on a base pointer the framework should be able to
realise what type exactly has been stored, create it and so on) in which
case is very clear why I had to use RTTI (because you just need the type
information of a base pointer/reference). I guess in this exception too can
be workarround with having the user specify the type behind the base
pointer/reference when serializing but seems awkward to me that way.
If not, then how is this achieved?
AFAIK as I said it uses RTTI :)

--
Dizzy
http://dizzy.roedu.net

Jan 3 '07 #2

"Dizzy" <di***@roedu.ne twrote in message
news:45******** *************** @news.sunsite.d k...
[rob desbois] wrote:
>Consider the following code:

try
{
// throws exceptions of several types
Foo();
}
catch (out_of_range& ex)
{ }
catch (exception& ex)
{ }

Given that this requires identification of object type at runtime, how
is this implemented -- does it use RTTI?

Exactly.
Yes, except not exactly. Try this:

- - -

#include <iostream.h>

class Base
{
public:
virtual ~Base()
{
// Base and its derivants are now RTTI-enabled - if needed...
}
};

class Super : public Base
{
};

int main()
{
Base *p;
try
{
p = new Super();
throw p;
}
catch( Super * )
{
cout << "Super" << endl;
}
catch( Base * )
{
cout << "Base" << endl;
}
delete p;
return 0;
}

- - -

So, if RTTI (run-time type information) were used to identify the
appropriate exception handler, this progam should print "Super".
However, the handler is determined in the compile-time, based
on the static type of the expression used in the throw-statement;
hence this program prints "Base".

To the original poster: All catch-blocks will get an entry point
in the object file. The entry points are categorized based on
the type of an object they catch. When a throw-statement is
compiled, the compiler emits code that scans the catch handler
of the category determined by the type of the expression in the
throw-statement: If you throw a Base *p [like in my example]
the catch handlers for a "Base *" are scanned. It does require
linker magic, but RTTI is definitely not necessary[*].

- Risto -
[*] Individual compiler implementors, however, are free to use
RTTI type_info structures in the exception implementation if they
deem it useful (and some indeed do).
Jan 3 '07 #3
Risto Lankinen wrote:
So, if RTTI (run-time type information) were used to identify the
appropriate exception handler, this progam should print "Super".
However, the handler is determined in the compile-time, based
on the static type of the expression used in the throw-statement;
hence this program prints "Base".
It is true that the type of the object (which is Base*) is used.
The VALUE of the object plays no roll in the selection of the
matching catch block. You can throw null pointers.
Dynamic typing is a feature of the pointed
to value.

It is NOT THE CASE that this can be determined at COMPILE time.
Imagine the following:

void Thrower() {
int i;
cin >i;
switch(i) {
case 1:
throw (Base*) 0;
case 2:
throw (Super*) 0;
default:
throw (int) 0;
}
}

int main() {
try {
Thrower();
} catch (Super*) { ...
catch (Base*) { ...
Jan 3 '07 #4
Risto Lankinen wrote:
[...] Try this:

- - -

#include <iostream.h>

class Base
{
public:
virtual ~Base()
{
// Base and its derivants are now RTTI-enabled - if needed...
}
};

class Super : public Base
{
};

int main()
{
Base *p;
try
{
p = new Super();
throw p;
}
catch( Super * )
{
cout << "Super" << endl;
}
catch( Base * )
{
cout << "Base" << endl;
}
delete p;
return 0;
}
Stylistic note: FAQ 17.7 rightly says that unless there is a good
reason not to, one should catch by reference rather than pointer as you
do here. I'd combine that with FAQ 18.1 to say that one should catch by
const reference unless there's a good reason not to.

Cheers! --M

Jan 3 '07 #5

"Ron Natalie" <ro*@spamcop.ne twrote in message
news:45******** **************@ news.newshostin g.com...
>
It is NOT THE CASE that this can be determined at COMPILE time.
And yet, it is the case. Let's reorder a bit and, hmm, compile...
int main() {
__main:
try {
Thrower();
} catch (Super*) { ...
..DATA SEGMENT __pSuper_handle rs
DW __main
DW __pSuper_handle r$main$filename = __pSuper_handle r
DW __main_unwrap
..CODE
__pSuper_handle r:
; code for the catch handler
catch (Base*) { ...
..DATA SEGMENT __pBase_handler s
DW __main
DW __pSuper_handle r$main$filename = __pSuper_handle r
DW __main_unwrap
..CODE
__pSuper_handle r:
; code for the catch handler

. . .

..CODE
__main_unwrap:
; code to unwrap this function call level if no handler found

void Thrower() {
int i;
cin >i;
switch(i) {
case 1: throw (Base*) 0;
1. locate [immediate/next] caller's stack frame
2. within data segment named __pBase_handler s...
3. is current return address between __XXX and __XXX_unwrap?
* No, call __XXX_unwrap and go back to 1
* Yes, jump to __pSuper_handle r$XXX$filename
case 2:
throw (Super*) 0;
Likewise here, except that two tables (pBase and pSuper) need
to be scanned, because Super is a derived class [however, even
this can be determined thru static analysis]

- - -

Linker magic I mentioned in my original article is twofold:

1. Unwrappers are generated everywhere where throwers are
located. There may well be more than one thrower for any given
type, but the linker should not complain about them having the
same name in the name table (and instead combine these into one
function only).

2. Data segments containing pointers to catch handlers may come
from multiple compilation units; linker must be able to consolidate
these tables so that the scanner routine finds all handlers.

Feel free to ask if my [hastily written] description is insufficient.

Cheers!

- Risto -
Jan 3 '07 #6

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

Similar topics

15
18041
by: Steven Reddie | last post by:
I understand that access violations aren't part of the standard C++ exception handling support. On Windows, a particular MSVC compiler option enables Microsoft's Structured Exception Handling (SEH) in C++ EH so that a catch (...) will catch an access violation. I don't know if other platforms support something similar. I'm wondering about how to best protect an application or library from poorly written user-defined callbacks. It...
8
1739
by: Adam H. Peterson | last post by:
Hello, I sometimes find myself writing code something like this: try { Derived &d=dynamic_cast<Derived&>(b); d.do_something_complicated(); // etc.... } catch (std::bad_cast) { throw Base_error("An object of incorrect type was given....");
2
1753
by: fred | last post by:
Hello, I read a file from several classes and want to catch an EOF when it appears. Having caught the EOF I want to allow the final part of the program to continue rather than just exiting. At present I use methods which read from the file; test the read was successful and return a 1 if not. This is then checked by the calling method, which also returns a 1 if the other method returned 1 (thus
9
4180
by: vijay21 | last post by:
hi all, This is about javascript window events. I have a simple html file like this <html> <head> </head> <body onmousedown="alert()"> <form> <input type="text">
7
2343
by: cmay | last post by:
FxCop complains every time I catch System.Exception. I don't see the value in trying to catch every possible exception type (or even figuring out what exceptions can be caught) by a given block of code, when System.Exception seems to get the job done for me. My application is an ASP.Net intranet site. When I catch an exception, I log the stack trace and deal with it, normally by displaying an error
37
2967
by: clintonG | last post by:
Has somebody written any guidelines regarding how to determine when try-catch blocks should be used and where their use would or could be considered superfluous? <%= Clinton Gallagher METROmilwaukee (sm) "A Regional Information Service" NET csgallagher AT metromilwaukee.com URL http://metromilwaukee.com/ URL http://clintongallagher.metromilwaukee.com/
12
6122
by: Vasco Lohrenscheit | last post by:
Hi, I have a Problem with unmanaged exception. In the debug build it works fine to catch unmanaged c++ exceptions from other dlls with //managed code: try { //the form loads unmanaged dlls out of which unmanaged exception //get thrown
3
1811
by: Peter A. Schott | last post by:
I know there's got to be an easy way to do this - I want a way to catch the error text that would normally be shown in an interactive session and put that value into a string I can use later. I've tried just using a catch statement and trying to convert the output to string, but this doesn't always work. I really don't have programs complex enough to do a lot of specific catching at this point - I just want to know: 1. something failed...
2
2369
by: Eric Lilja | last post by:
Hello, consider this complete program: #include <iostream> #include <string> using std::cout; using std::endl; using std::string; class Hanna {
0
10770
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
10481
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10524
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
9312
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
7741
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
5616
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
4409
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
2
3956
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3074
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.