Catch an exception with reference-parameter

Share the Article

When an object is thrown as exception then catch block should have its parameter declared by reference and not by value. In that way the same object will be assigned to reference variable.

#include <iostream> //main header using namespace std;//for namespace class MainFunda { public: MainFunda(){ cout << "MainFunda()" << endl; } A(const MainFunda& rhs) { cout << "MainFunda(copy constructor)" << endl; } ~MainFunda() { cout << "~MainFunda()" << endl; } }; int main() { try { cout << "Starting try block" << endl; throw MainFunda(); cout << "Ending try block" << endl; } catch (MainFunda& a) { cout << "Exception caught in catch(MainFunda&) : " << endl; } return 0; }

The output:

Starting try block MainFunda() Exception caught in catch(MainFunda&) : ~MainFunda()

However, it is still possible to catch the exception by value, but there are 2 main problems in this approach

catch (MainFunda a) //catch by value { cout << "Exception caught in catch(MainFunda) : " << endl; }

Copy Construction: First problem is that the constructor creates a new duplicate copy of thrown object. This parameter variable gets the copy and not original exception. The compiler invokes copy constructor to create this duplicate copy object

The compiler produces following output with such catch block:

Starting try block MainFunda() MainFunda(copy constructor) Exception caught in catch(MainFunda) : ~MainFunda() ~MainFunda()

Object Slicing: Second, problem happens in case of inheritance. This is a scenario, when the argument is of type base class and exception is of type derived object. Here, compiler will slice the Derived class object. The exception object is initially of type Derived class but when it reaches inside the catch block it will become a Base object due to such slicing.

#include <iostream> //main header using namespace std; //for namespace class MFBase { public: virtual void printtype() { cout << "Base Object" << endl; } }; class MFDerived : public MFBase { public: virtual void printtype() { cout << "Derived Object" << endl; } }; int main() { try { cout << "Starting try block" << endl; throw MFDerived(); cout << "Ending try block" << endl; } catch (MFBase b) //MFBase type, catch by value { cout << "Exception caught" << endl; b.printtype(); } return 0; }

The output is as follows:

Starting try block Exception caught Base Object

The correct way to specify catch in this example is by reference:

catch (MFBase& b)//Base type parameter, catch by reference { cout << "Exception caught" << endl; b.printtype(); }

The output will be as follows:

Starting try block Exception caught Derived Object

When multiple catch blocks match the type of exception thrown

In such case, the compiler will call the first catch block which matches the exception, and it ignores all the other catch blocks. The compiler will ignore the other catch blocks even if they are compatible. However, compiler shall generate warnings in such cases.

#include <iostream> //main header using namespace std;//for namespace class MFBase { public: virtual void printtype() {cout << "Base" << endl; } }; class MFDerived : public MFBase { public: virtual void printtype() {cout << "Derived Object" << endl; } }; int main() { try { cout << "Starting try block" << endl; throw MFDerived(); cout << "Ending try block" << endl; } catch (MFBase& b) { cout << "Exception caught : MFBase&" << endl; b.printtype(); } catch (MFDerived& b) { cout << "Exception caught : MFDerived&" << endl; b.printtype(); } return 0; }

The output is:

compiler warning when an exception  is caught by a handler which occurs earlier than a more suitable

Main Funda: The exception object must always be caught by reference otherwise it creates problems

Related Topics:

Why a destructor should never throw exception?
What is the problem with setjmp( ) & longjmp( ) ?
Basics of throwing and catching exception
What happens when exception thrown from a constructor?
Re-throwing an exception
What are function level try-catch blocks
Understanding exception specification for functions
Explaining C++ casts
How pointer to class members are different ?
What is reference collapsing?
How to make a class object un-copyable?

Share the Article

267 thoughts on “Catch an exception with reference-parameter

  1. Of course, your article is good enough, slotsite but I thought it would be much better to see professional photos and videos together. There are articles and photos on these topics on my homepage, so please visit and share your opinions.

  2. Transmission occurs primarily through the direct spread of adults, nymphs, or eggs from infested bedding, furniture, or even clothing and personal items, such as handbags buy online cialis Plasma concentrations of morphine, morphine 3 glucuronide, and morphine 6 glucuronide after intravenous and oral administration to healthy volunteers relationship to nonanalgesic actions

  3. While hormonal therapies are the mainstay of treatment for VMS, there is a clear need for safe and effective nonhormonal treatment options for women who choose not to use hormone therapy and for those in whom hormone therapy is not effective cialis reviews

  4. Ръководство за родители Мини Бингото представлява онлайн вариант, при който разполагате с 9 квадрата и 30 топки. Числата се теглят супер бързо и секунди след това можете да разберете дали сте спечелили. Тази игра се предлага предимно безплатно само за забавление и по-рядко с истински пари. Запазване на името, имейл адреса и уебсайта ми в този браузър за следващия път когато коментирам. 1 – Бинго с 30 топки Silentbet предоставя на своите потребители възможността да опознаят бингото напълно безплатно. Това не изисква финансов депозит, нито инсталация на специален софтуер от типа на Flash Player. Игрите на сайта разчитат на HTML5 технология, което прави пускането им бързо и лесно. https://cristianjzmb097532.xzblogs.com/55362285/бетуей-казино-вегас-секция-игри Ротативките с плодове са отделен жанр слот машини, в които се използват символи на плодове, като череши, дини, банани, праскови и други. Модерните ротативки с плодове се ползват с голямо търсене в хазартните среди, но в същото време мнозина все още играят класически ротативки с плодове от носталгия. Сред останалите популярни разработчици на казино игри можем да отличим компании като Microgaming и тяхната най-популярна слот игра Mega Moolah. Напълно безплатно в сайта на Betenemy може да играете и още много други техни тематични заглавия, като например Game of Thrones или пък Hitman Slot.

  5. generic for cialis 42 Additionally, NAC has a hepatoprotective effect on liver injury during TB treatment Table 1, 43, 44 and a murine macrophage model has illustrated the ability of NAC to potentiate the efficacy of TB chemotherapy, specifically in combination with isoniazid

  6. You actually make it seem really easy together with your presentation however I find this matter to be really something which I think I’d by no means understand. It sort of feels too complicated and extremely wide for me. I’m taking a look forward for your next publish, I’ll try to get the dangle of it!

  7. What i do not realize is in truth how you are not really much more smartly-preferred than you might be now. You are very intelligent. You know therefore significantly in terms of this subject, produced me in my view imagine it from so many various angles. Its like women and men are not interested unless it is something to do with Girl gaga! Your individual stuffs outstanding. At all times handle it up!

  8. Of course, your article is good enough, bitcoincasino but I thought it would be much better to see professional photos and videos together. There are articles and photos on these topics on my homepage, so please visit and share your opinions.

  9. certainly like your website but you have to test the spelling on quite a few of your posts. Many of them are rife with spelling problems and I to find it very troublesome to inform the truth on the other hand I will definitely come again again.

  10. Unquestionably imagine that that you said. Your favorite reason appeared
    to be at the web the easiest factor to have in mind of.

    I say to you, I certainly get irked even as people
    consider worries that they just do not recognize about.
    You controlled to hit the nail upon the top and also outlined out the entire thing with no need side effect , other folks can take a
    signal. Will probably be back to get more.
    Thank you

    My blog post … tracfone special coupon 2022

  11. certainly like your web-site however you have to test the spelling on several of your posts. Several of them are rife with spelling issues and I to find it very bothersome to tell the truth then again I?¦ll surely come again again.

  12. With the development of receptor specific antagonists, additional information about the roles of the receptors and endogenous cannabinoids in the modulation of pain has been obtained stromectol online canada Tests for in vitro transformation in rat and Syrian hamster embryo cells gave positive results, while results in mouse cells were negative IARC, 1987b

  13. A formidable share, I simply given this onto a colleague who was doing somewhat evaluation on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love reading extra on this topic. If doable, as you change into expertise, would you thoughts updating your weblog with extra details? It is highly useful for me. Large thumb up for this blog put up!

  14. Virtually all of the things you claim happens to be supprisingly accurate and that makes me wonder why I hadn’t looked at this in this light previously. Your article truly did turn the light on for me as far as this specific issue goes. Nevertheless at this time there is actually 1 point I am not necessarily too comfy with so whilst I try to reconcile that with the actual central theme of your position, allow me see just what all the rest of the subscribers have to say.Nicely done.

  15. I am also commenting to let you be aware of what a helpful experience our daughter experienced going through your blog. She came to find numerous details, which include what it’s like to possess an awesome helping mood to let others without problems master some tortuous subject matter. You actually exceeded her expectations. Thanks for imparting the productive, trustworthy, informative as well as easy thoughts on your topic to Jane.

  16. Very interesting info !Perfect just what I was searching for! “The most wasted day of all is that on which we have not laughed.” by Sbastien-Roch Nicolas de Chamfort.

  17. Zhou and colleagues 19 used nuclear extracts from a wide variety of cell types of human, rat and murine origin to show, using EMSAs, that SOX9 binds strongly to the 48 bp Col2a1 intron 1 sequence and bends it at this site, strongly activating the 48 bp enhancer as well as larger Col2a1 enhancer elements lasix and kidney function In rare cases, gynecomastia may recur but this does not relate to the surgery itself

  18. Good day! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Thanks!

  19. Porn pornstars video porn cutie xxx stoya fuck workout sex
    monroe female saggy porn is jameson danger sex movies
    creampie gangbang extrem movie table nude pron milf may porn office orgy movies masturbation joins hot body video sex amateur porn for downblouse videos xxx snow video bound beautiful xxx morgan female young cock african tit missionary nude porn library.

  20. Složeni tkanje Veza između testosterona i gubitka
    kose je komplicirana. Popularno je vjerovanje da ćelavi muškarci imaju visoku razinu testosterona,
    no je li to zaista istina? Ćelavost muškaraca ili androgena alopecija utječu
    na procijenjeno 50 milijuna muškaraca i 30 milijuna žena u Sjedinjenim
    Državama, prema Nacionalni institut za zdravlje (NIH). Gubitak.

  21. तब मैंने उन भेड़ों को जो
    ज़बह हो रही थीं, या’नी गल्ले के मिस्कीनों को चराया और मैंने दो लाठियाँ लीं; एक का नाम
    फ़ज़ल रख्खा और दूसरी का इत्तिहाद, और गल्ले को.

  22. Wonderful post however , I was wondering if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit further. Many thanks!

  23. Thanks, I have recently been looking for information approximately this topic for a while and yours is the greatest I’ve came upon till now. However, what concerning the bottom line? Are you sure about the source?

  24. After I initially left a comment I appear to have clicked on the -Notify
    me when new comments are added- checkbox and from
    now on every time a comment is added I recieve four emails with the exact same comment.
    There has to be an easy method you can remove me from that service?
    Cheers!

  25. Hey there! I could have sworn I’ve been to this website before
    but after reading through some of the post I realized it’s new to
    me. Anyhow, I’m definitely happy I found it and I’ll be book-marking and checking back often!

  26. Most men who use Viagra and other ED medications do so legally after receiving a valid prescription from their healthcare provider priligy 30mg tablets Do not take this medication with any other product that contains tadalafil or other similar medications used to treat erectile dysfunction-ED or pulmonary hypertension such as sildenafil, vardenafil

  27. I needed to thank you for this wonderful read!!
    I certainly enjoyed every little bit of it. I have got you saved as a
    favorite to look at new things you post…

    Also visit my homepage: tracfone

  28. Augustine Badon s face changed horribly, and he was speechless I have always believed in the principle of not committing crimes against what are the side effects of taking viagra crimes cialis online without prescription EstГЎn todos en la misma sintonГ­a, con diferentes fortalezas que se complementan unas a otras, y el lugar funciona como una mГЎquina bien aceitada

  29. It is in reality a nice and useful piece of info. I’m happy
    that you simply shared this helpful information with
    us. Please keep us informed like this. Thank you for sharing.

  30. Just wish to say your article is as astonishing. The clarity in your post is simply great and i can assume you’re
    an expert on this subject. Well with your permission allow me to grab your RSS feed
    to keep updated with forthcoming post. Thanks a million and please keep up the
    enjoyable work.

  31. Spot on with this write-up, I really believe that this website needs far more attention. I’ll probably be returning to read more,
    thanks for the information!

  32. When someone writes an paragraph he/she keeps the idea of a user in his/her
    brain that how a user can know it. Therefore that’s why this article is great.
    Thanks!

    Feel free to visit my website: coupon

  33. Gebelik öncesi ilaç kullanarak gebe kaldıysanız ve
    tansiyonunuz normalse bile ‘kronik hipertansif’ kabul edilirsiniz.
    Gebeliğin ikinci üç ayında tansiyon.

  34. hey there and thank you for your information – I’ve certainly picked up something new from right here.
    I did however expertise several technical points using this website, since I experienced to reload the website lots of times
    previous to I could get it to load correctly. I had been wondering if your web host is OK?
    Not that I’m complaining, but slow loading instances times will very
    frequently affect your placement in google and can damage your high-quality score if ads and marketing with Adwords.
    Well I’m adding this RSS to my e-mail and can look out for a
    lot more of your respective intriguing content.
    Ensure that you update this again very soon.

  35. I’m impressed, I have to admit. Seldom do I encounter a blog that’s equally educative
    and engaging, and without a doubt, you’ve hit the
    nail on the head. The issue is something which too few men and
    women are speaking intelligently about. Now i’m very happy that I stumbled across this during
    my hunt for something relating to this.

  36. This is the perfect blog for anybody who hopes to understand this topic.
    You understand so much its almost hard to argue with you (not
    that I actually would want to…HaHa). You certainly put a fresh spin on a
    subject that has been written about for years.
    Excellent stuff, just excellent!

  37. hey there and thank you for your info – I have certainly picked up something new from right here.
    I did however expertise several technical issues using this website, since I experienced to
    reload the website lots of times previous to I could get it to load properly.
    I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will sometimes affect your placement in google and could damage your quality score if
    ads and marketing with Adwords. Well I am adding this RSS
    to my e-mail and could look out for much more of your respective interesting content.
    Make sure you update this again very soon.

  38. 314262 316837You produced some very first rate factors there. I seemed on the internet for the difficulty and located a lot of people will go along with together together with your internet site. 68194

  39. I do agree with all of the ideas you’ve presented in your post. They’re very convincing and will definitely work. Still, the posts are too short for newbies. Could you please extend them a bit from next time? Thanks for the post.

  40. Aw, this was a really nice post. In thought I would like to put in writing like this additionally – taking time and precise effort to make an excellent article… but what can I say… I procrastinate alot and on no account appear to get something done.

  41. 537829 820180We offer the top practical and most applicable solutions. All our Sydney plumbers are experienced and qualified and are able to speedily assess your problem and locate the top solution. 940105

  42. Hi my loved one! I wish to say that this article is awesome, nice written and come with approximately all important infos.
    I’d like to see extra posts like this .

  43. I’ve been exploring for a bit for any high quality articles or weblog posts on this kind of space .
    Exploring in Yahoo I finally stumbled upon this website.
    Studying this information So i’m satisfied to express that
    I’ve a very good uncanny feeling I found out exactly what I needed.
    I such a lot indubitably will make certain to do not
    forget this site and give it a glance on a continuing basis.

  44. I’m impressed, I must say. Seldom do I encounter a
    blog that’s both educative and amusing, and let me tell you, you’ve hit the nail on the head.
    The problem is an issue that too few men and women are speaking intelligently about.
    I’m very happy I stumbled across this in my search for something
    relating to this.

  45. Undeniably imagine that that you said. Your favourite justification seemed to
    be on the internet the easiest thing to be
    aware of. I say to you, I definitely get irked whilst people consider concerns that they just don’t realize about.
    You managed to hit the nail upon the top and outlined
    out the whole thing without having side effect , folks can take a signal.

    Will likely be again to get more. Thank you

  46. I have been exploring for a little bit for any
    high-quality articles or weblog posts on this kind of house .
    Exploring in Yahoo I ultimately stumbled upon this site.
    Reading this info So i am satisfied to exhibit that I have an incredibly
    just right uncanny feeling I found out exactly
    what I needed. I so much certainly will make certain to don?t fail to
    remember this web site and provides it a look regularly.

  47. Do you mind if I quote a couple of your articles as long as
    I provide credit and sources back to your blog? My website
    is in the exact same area of interest as yours
    and my users would really benefit from some
    of the information you provide here. Please let me know
    if this okay with you. Many thanks!

  48. We’re a bunch of volunteers and starting a brand
    new scheme in our community. Your website offered us with
    helpful info to work on. You have done a formidable task and our whole neighborhood will probably be grateful to you.

  49. Yesterday, while I was at work, my sister stole my iPad and tested
    to see if it can survive a forty foot drop, just so she can be a youtube sensation. My apple ipad is now
    broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  50. Having read this I believed it was really enlightening.
    I appreciate you finding the time and energy to put this information together.
    I once again find myself spending way too much time both reading and commenting.
    But so what, it was still worthwhile!

  51. Howdy! I know this is somewhat off topic but I
    was wondering which blog platform are you using for this website?

    I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking
    at alternatives for another platform. I would be great
    if you could point me in the direction of a good platform.

  52. I was recommended this website by my cousin. I’m not sure whether this post is written by him as nobody else know
    such detailed about my difficulty. You are amazing!
    Thanks!

  53. 257299 551701Someone essentially assist to make severely posts I may well state. That will be the very very first time I frequented your internet site page and so far? I surprised with the analysis you made to create this certain submit incredible. Magnificent task! 203619

  54. 478078 930023This web page is often a walk-through for all with the details it suited you with this and didnt know who to ask. Glimpse here, and you will certainly discover it. 408671

  55. 820352 901971Someone essentially lend a hand to make critically articles Id state. That will be the very first time I frequented your internet site page and so far? I amazed with the research you made to create this actual post extraordinary. Great activity! 542066

  56. 543017 265550This design is spectacular! You certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (properly, almostHaHa!) Wonderful job. I genuinely enjoyed what you had to say, and a lot more than that, how you presented it. Too cool! 749246

Leave a Reply

Your email address will not be published. Required fields are marked *