+ 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
8 ответов
+ 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);
+ 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();
}
+ 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.
+ 1
You're welcome brother 😊
+ 1
Appreciate that Bob_Li
+ 1
Sounds good Bob_Li
0
I changed it to string rather than const char* , but still same behaviour