handling exceptions

R

Richard Herring

annex <[email protected]> said:
hi, i have some queries about handling exceptions, i'm using Borland c++
Builder 6.

1) what's the best way to catch multiple exceptions in one catch statement?
is this possible? for e.g i want to catch 2 exceptions; MyEx1 and MyEx2,
both to be handled in the same way. how to do this?

try
{
doSomething();
}
catch (MyEx1)
{
sameCode();
}
catch (MyEx2)
{
sameCode();
}

note that both exceptions are to be handled using the same piece of code.

Lots of answers, but nobody seems to have answered this directly.
Answer: derive both from a common base class and catch by reference:

class MyExBase {...}
class MyEx1: public MyExBase {...}
class MyEx2: public MyExBase {...}

try
{
doSomething();
}
catch (MyExBase &)
{
sameCode();
}
2) what's the difference btw catch(...) and catch(Exception). will
catch(Exception) catch all unhandled exceptions also like does catch(...) ?

No. But catch(Exception&) will catch anything derived from Exception.
 
S

Siemel Naran

Richard Herring said:
Lots of answers, but nobody seems to have answered this directly.
Answer: derive both from a common base class and catch by reference:

My response, the first one, answered everything as yours.
 
T

tom_usenet

/* should only be called within a catch block
*/
void myhandler()
{
try
{
throw;
}
catch ( MyEx1 const & )
{
}
catch ( MyEx2 const & )
{
}
//handle both cases ...
}


void f()
{
try
{
// something that throws
}
catch ( ... )
{
myhandler();
}
}

I've never used it, or seen it used (except in NG posts).

I "re-invented" the idiom when interfacing with Java via JNI. You
can't let C++ exceptions propogate into Java for obvious reasons (BOOM
goes the VM), and the above allowed me to have a single handler to map
C++ exceptions to Java ones.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top