Why exception is not handled | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Why exception is not handled

Hi I have tried throwing exception from constructor. It is handled inside main function where object was created. Why it still terminates ? Should it not been handled by try catch? https://sololearn.com/compiler-playground/cvX6oq14e546/?ref=app

18th Apr 2024, 4:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
8 Antworten
19th Apr 2024, 4:18 AM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar
+ 2
Oh thanks again. I got it now. I was simply using throw and it would work if I would have used throw runtime_error(s); Instead of throw(s);
19th Apr 2024, 4:32 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Ketan Lalcheta interesting... since you throw a string, you can also catch a string...🤯. try { A obj; } catch(const string& ex) { cout << ex; } but this is not advised, so the proper way is to wrap it in a runtime_error or a custom exception. using a struct is simpler, but it's just a preference. The simplest is to just wrap it in a runtime_error, as you mentioned. #include <exception> struct oops: std::exception{ const char* what() const noexcept{ return "Oops!\n"; } } try{ throw oops(); }catch(std::exception& ex){ std::cout<<ex what(); }
20th Apr 2024, 3:30 AM
Bob_Li
Bob_Li - avatar
+ 1
You're throwing a C-style string (const char*) in the constructor of class A, but you're catching a C++ exception (const exception&) in the main function. This is why the exception is not caught.
18th Apr 2024, 6:43 PM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar
+ 1
You're welcome brother 😊
19th Apr 2024, 4:33 AM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar
+ 1
Appreciate that Bob_Li
20th Apr 2024, 5:01 AM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar
+ 1
Sounds good Bob_Li
20th Apr 2024, 6:03 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I changed it to string rather than const char* , but still same behaviour
19th Apr 2024, 4:05 AM
Ketan Lalcheta
Ketan Lalcheta - avatar