473,320 Members | 1,746 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Catching base class Exception as Reference.

Expand|Select|Wrap|Line Numbers
  1. class BaseExcep
  2. {
  3. protected:
  4.       std::string message;
  5.  
  6. public:
  7.       BaseExcep(std::string);
  8.       virtual void printException();
  9.  
  10. };
  11.  
  12. class DerivedExcep1 : public BaseExcep
  13. {
  14. public:
  15.       DerivedExcep1(std::string);
  16. };
  17.  
  18. class DerivedExcep2 : public DerivedExcep1
  19. {
  20. public:
  21.      DerivedExcep2(std::string);
  22. };
  23.  
  24. int main()
  25. {
  26. try
  27. {
  28.   throw DerivedExcep2("Derived2");
  29. }
  30. catch(BaseExcep& ex)
  31. {
  32. / *
  33.   * Here i need to find which exception type is actually thrown
  34.   * whether it is DerivedExcep1 or DerivedExcep2 or  
  35.   * BaseExcep itself.
  36.   * i cant use dynamic_cast in this, since it is a reference
  37.   * can someone help me out
  38.   */
  39. }
  40.  
Jul 23 '13 #1

✓ answered by weaknessforcats

There is a question here.

If you have 50 exception types, then you catch each type explicitly as Banfa suggests.

However, if you have a polymorphic hierarchy then you only need catch a base class reference since the hierarchy interface is in the base class. If you need to know the exact type, then implement a virtual base::what() method. The derived class overrides this method and puts in its own stuff. Like maybe the derived class name.

BTW: A base class reference is not the same as a derived class reference. You should be catching base class pointers or catching a smart pointer to the base class.

In any case, nix with the casting. Casting in C++ means you are calling old legacy C code with void* stuff or your C++ design is flawed.

Have you considered using a Visitor?

5 2657
Banfa
9,065 Expert Mod 8TB
If you need to handle your different exceptions differently then catch them explicitly

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.   try
  4.   {
  5.     throw DerivedExcep2("Derived2");
  6.   }
  7.   catch(DerivedExcep1& ex)
  8.   {
  9.     // Handle derived exception 1
  10.   }
  11.   catch(DerivedExcep2& ex)
  12.   {
  13.     // Handle derived exception 2
  14.   }
  15.   catch(BaseExcep& ex)
  16.   {
  17.     // Handle base exception
  18.   }
  19.  
  20. }
Jul 23 '13 #2
Banfa, Thanks for ur reply, but in my application i have more than 50 Exception classes, and more than 100 files i am using those exceptions, so i cant catch each exception for every case in all files, i can catch the base exception up-to some hierarchy and can do some operation based on the catched exception. For Eg, There are some cases,


ExceptionHirearchy
==================

HeadExcep
|
BaseExcep1 BaseExcep2 BaseExcep3 ..........
| |
Deri1 Deri2 Deri3 Sub1 Sub2 ......................
Expand|Select|Wrap|Line Numbers
  1.       try
  2.       {  
  3.         try
  4.         {
  5.           try
  6.           {
  7.               throw DerivedExcep3("aaaaaa");
  8.           }
  9.           catch(DerivedExcep3& ex)
  10.           {
  11.               ex.setMark();
  12.               throw;
  13.           }
  14.            func1();// throws DerivedExcep2
  15.            func2(); //throws DerivedExcep1
  16.  
  17.         }
  18.         catch(BaseExcep1& ex)
  19.         {
  20.            BaseExcep3 exc;
  21.            exc.setCause(ex);
  22.            throw exc;
  23.         }
  24.         func3();// throws BaseExcep1
  25.         func4();//throws BaseExcep 2
  26.      }
  27.      catch(HeadExcep& ex)
  28.      {
  29.        /*
  30.         * Here i want to know which exception type is actually thrown
  31.         * or else at-least i want to whether the actual Exception 
  32.         * thrown is DerivedExcep4
  33.         * pls let me know your comments on this
  34.         */
  35.      }
  36.  
Jul 24 '13 #3
weaknessforcats
9,208 Expert Mod 8TB
There is a question here.

If you have 50 exception types, then you catch each type explicitly as Banfa suggests.

However, if you have a polymorphic hierarchy then you only need catch a base class reference since the hierarchy interface is in the base class. If you need to know the exact type, then implement a virtual base::what() method. The derived class overrides this method and puts in its own stuff. Like maybe the derived class name.

BTW: A base class reference is not the same as a derived class reference. You should be catching base class pointers or catching a smart pointer to the base class.

In any case, nix with the casting. Casting in C++ means you are calling old legacy C code with void* stuff or your C++ design is flawed.

Have you considered using a Visitor?
Jul 25 '13 #4
@weaknessforcats, Thanks for ur reply, As u said i have implemented a similar functionality like what(), and it is working fine.:), But u said something about Visitor, what is that, it is a concept in c++?
Aug 19 '13 #5
weaknessforcats
9,208 Expert Mod 8TB
A Visitor is a design pattern. A design pattern is a generic solution to problems often encountered in software development.

Visitor can be used when a class was developed and implemented and later, maybe years later, you find out you need to add a bunch of data members to the original class. Visitor lets you add these members to a new class and then visit the original class o pick up the original data.

Read this: http://bytes.com/topic/c/insights/67...tterns-visitor

There are C++ Insights articles for other design patterns.
Aug 19 '13 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Dave | last post by:
try { ... } catch (exception e) { cout << e.what() << endl; } In the code above, e is caught by value rather than polymorphically (assume
2
by: Andrew G. J. Fung | last post by:
Can anyone please explain to me why the code below throws an exception? It seems to occur when deserializing an instance of a subclass, whose base class holds a struct, where said struct holds an...
5
by: Chris Capon | last post by:
Is there any way to cast a base class object to a derived class datatype when the derived class adds no new fields nor alters the object allocation in any way? The scenario would be where you...
2
by: Locia | last post by:
Can I cast from base class to derive class? class A { } class B:A {
12
by: Andrew Schepler | last post by:
When compiled with Visual C++ .NET 2003 (only), the program below aborts as though no matching catch clause is present. If the copy constructor of A is made public, it successfully catches the...
8
by: Brett Romero | last post by:
I have this situation: myEXE <needs< DerivedClass <which needs< BaseClass Meaning, myEXE is using a type defined in DerivedClass, which inherits from BaseClass. I include a reference to...
2
by: RitualDave | last post by:
I get a C2811 error when I compile the following (with the /clr switch): template <class T> ref class Base {}; template <template <class> class TBase> ref class Derived : TBase<int> {};
1
by: Belebele | last post by:
I would like to have the compiler bind a Base class const reference to a temporary object of a Derived class when calling another class constructor. Please see the code below: class Base {}; ...
15
by: Bob Johnson | last post by:
I have a base class that must have a member variable populated by, and only by, derived classes. It appears that if I declare the variable as "internal protected" then the base class *can*...
4
by: YaldenWere | last post by:
On gnu compiler: If you try to initialize a reference to a pointer to a base type, (e.g. Foo*&), with a pointer to a derived type, eg Bar*, the compiler rejects it claiming inability to match...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.