473,657 Members | 2,800 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Try blocks and not catching exceptions

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....");
}

The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.

On the other hand, if a bad_cast exception is thrown in
do_something_co mplicated(), I don't want my catch block to catch that.
The catch block is only for catching and translating an error if it
occurs at _this_ dynamic_cast. However, I can't simply move
do_something_co mplicated() out of the try block, as that will be outside
d's scope.

I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code. Also, there are cases where I'm
catching an exception from a constructor or something, where it's either
impossible or unadvisable to split the declaration and the
initialization of a variable, so the declaration really has to be inside
the try block.

What is the best way to handle this type of situation, so that I can
catch the exception I'm looking for, but not other exceptions in the
same scope that happen to be of the same type?
Jul 22 '05 #1
8 1730

"Adam H. Peterson" <ah**@email.byu .edu> wrote in message news:bv******** ***@acs2.byu.ed u...
I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code.


I don't know why it's more verbose (unless you thing -> is a lot more verbose than
..).

Derived* dp = dynamic_cast<De rived*>(&b);
if(dp) throw Base_error("An object of the wrong type...");

dp->do_something_c omplicated();

Actually looks like less code to me. Exceptions suck for errors that are
easily tested for by other means.

Jul 22 '05 #2


Adam H. Peterson wrote:
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....");
}

The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.


If you don't know already know that b is a Derived why are you
downcasting to a reference? If you don't cast to a reference you won't
get an exception.

QUERY: Is this sort of thing exceptional programming or what?

Jul 22 '05 #3
On Tue, 27 Jan 2004 03:39:59 -0700, "Adam H. Peterson"
<ah**@email.byu .edu> wrote:
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....");
}

The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.

On the other hand, if a bad_cast exception is thrown in
do_something_c omplicated(), I don't want my catch block to catch that.
The catch block is only for catching and translating an error if it
occurs at _this_ dynamic_cast. However, I can't simply move
do_something_c omplicated() out of the try block, as that will be outside
d's scope. What is the best way to handle this type of situation, so that I can
catch the exception I'm looking for, but not other exceptions in the
same scope that happen to be of the same type?


Derived& d = f(b);
d.do_something_ complicated();

Where f has the try/catch block. You could create a generic version of
f:

template <class Derived, class Base, class ErrorHandler>
Derived& checked_dynamic _cast(Base& b, ErrorHandler eh)
{
try
{
return dynamic_cast<De rived&>(b);
}
catch(std::bad_ cast const&)
{
return eh(); //may throw, return a default, or whatever
}
}

Derived& d = checked_dynamic _cast<Derived&> (b, base_error_thro wer());
or similar.

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #4

"tom_usenet " <to********@hot mail.com> wrote in message news:4h******** *************** *********@4ax.c om...
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....");
}
Derived& d = f(b);
d.do_something_ complicated();

Where f has the try/catch block. You could create a generic version of
f:

try { dynamic_cast<De rived&>(b); } castch (std::basd_cast ) { throw Base_error("... "); } // probe for mines
Derived& d = dynamic_cast<De rived&>(b);
d.do_something_ complicated();
Jul 22 '05 #5
On Tue, 27 Jan 2004 03:39:59 -0700, Adam H. Peterson wrote:
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....");
}

The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.

On the other hand, if a bad_cast exception is thrown in
do_something_co mplicated(), I don't want my catch block to catch that.
The catch block is only for catching and translating an error if it
occurs at _this_ dynamic_cast. However, I can't simply move
do_something_co mplicated() out of the try block, as that will be outside
d's scope.

I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code. Also, there are cases where I'm
catching an exception from a constructor or something, where it's either
impossible or unadvisable to split the declaration and the
initialization of a variable, so the declaration really has to be inside
the try block.


Read Rons excelent answer first. Now still want to do this?

Derived *p=dynamic_cast <Derived&>(b) ;
if (!p)
throw Base_error("An object of incorrect type was given....");
Derived &d=*p;
d.do_something_ complicated();
// etc....

Or follow Toms advice and wrap this in a function:

Derived &down_cast(B ase &b)
{
Derived *p=dynamic_cast <Derived&>(b) ;
if (!p)
throw Base_error("An object of incorrect type was given....");
return *p;
}

Derived &d=down_cast(b) ;
d.do_something_ complicated();

HTH,
M4

Jul 22 '05 #6
Martijn Lievaart wrote:
On Tue, 27 Jan 2004 03:39:59 -0700, Adam H. Peterson wrote:

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....");
}

The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.

On the other hand, if a bad_cast exception is thrown in
do_something_ complicated(), I don't want my catch block to catch that.
The catch block is only for catching and translating an error if it
occurs at _this_ dynamic_cast. However, I can't simply move
do_something_ complicated() out of the try block, as that will be outside
d's scope.

I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code. Also, there are cases where I'm
catching an exception from a constructor or something, where it's either
impossible or unadvisable to split the declaration and the
initializatio n of a variable, so the declaration really has to be inside
the try block.

Read Rons excelent answer first. Now still want to do this?

Derived *p=dynamic_cast <Derived&>(b) ;


/* ITYM */ Derived *p=dynamic_cast <Derived*>(b) ;
if (!p)
throw Base_error("An object of incorrect type was given....");
Derived &d=*p;
d.do_something_ complicated();
// etc....

Or follow Toms advice and wrap this in a function:

Derived &down_cast(B ase &b)
{
Derived *p=dynamic_cast <Derived&>(b) ;
/* ITYM */ Derived *p=dynamic_cast <Derived*>(b) ;
if (!p)
throw Base_error("An object of incorrect type was given....");
return *p;
}

Derived &d=down_cast(b) ;
d.do_something_ complicated();

HTH,
M4


Jul 22 '05 #7
On Tue, 27 Jan 2004 08:04:11 -0500, Jeff Schwab wrote:

/* ITYM */ Derived *p=dynamic_cast <Derived*>(b) ;
/* ITYM */ Derived *p=dynamic_cast <Derived*>(b) ;


Auch. Yes.

M4

Jul 22 '05 #8
Ron Natalie wrote:
"Adam H. Peterson" <ah**@email.byu .edu> wrote in message news:bv******** ***@acs2.byu.ed u...
I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code.
I don't know why it's more verbose (unless you thing -> is a lot more verbose than
.).

Derived* dp = dynamic_cast<De rived*>(&b);
if(dp) throw Base_error("An object of the wrong type...");


'if (!dp) ...' ?
dp->do_something_c omplicated();

Actually looks like less code to me. Exceptions suck for errors that are
easily tested for by other means.


--
Best regards,
Andrey Tarasevich

Jul 22 '05 #9

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

Similar topics

1
2972
by: Rolf | last post by:
I understand a compilation error occurs when a method that throws no exceptions is the only code in a try block. What I don't understnad is why I can specify the catching of an Exception for a method that throws no exceptions, but I cannot catch an IOException for a method that throws no exceptions? // This try/catch code complies fine, even though foo2 throws no exceptions:
2
1767
by: Keith Bolton | last post by:
I am handling exceptions currently using try, except. Generally I don't handle specific exceptions and am catching all. Then if an exception occurs, I would like to capture that error string. However, in the documentation it seems like there is not a way to get the extra str data if you are handling all exceptions and not specifically. Is there? thanks -keith
7
2332
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
12
6102
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
7
6383
by: Derek Schuff | last post by:
I'm sorry if this is a FAQ or on an easily-accesible "RTFM" style page, but i couldnt find it. I have some code like this: for line in f: toks = line.split() try: if int(toks,16) == qaddrs+0x1000 and toks == "200": #producer write prod = int(toks, 16)
5
2226
by: Simon Tamman | last post by:
I have an object named DisasterRecovery. The Ctor of this object is this: private DisasterRecovery() { Application.ThreadException+= new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); }
0
801
by: ticean | last post by:
I'm using the Enterprise Exception Handling Blocks. I'm catching exceptions by ExceptionType and Policy, wrapping them and sending them up the chain. My problem is that I'm finding it very difficult to display a useful message to the user. Can anyone give me an overview on adding context information to the handled exceptions and retrieving that context information for display to the user? And, I need to know how to retreive the...
4
1803
by: lovecreatesbea... | last post by:
Is the following code (without any code at lines x and x + 3) correct? Is it better to call exit() or re-throw the exceptions at line x and line x + 3?. What is the better code should we place at line x and line x + 3? try { cnn = env->createConnection(user, pwd, db); } catch (SQLException &esql){ cerr << "DB Exception: " << esql.getMessage(); /* line x ? */
9
2793
by: GiJeet | last post by:
Hello, I come from the VB6 world where we'd put a single ON ERROR GOTO ErrHandler at the top of a method. Now whenever an error happened it would drop into the ErrHandler code. In .Net it seems like you have too many Try/Catch statements all throughout the code. I think this is ugly error handling. Is there a better way to handle exceptions in .Net 2.0 + then putting all these Try/Catch blocks around code? G
0
8403
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
8316
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
8610
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...
1
6174
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
5636
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
4168
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...
0
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2735
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
1967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.