If I am catching BaseException
will this also catch exceptions which derive from BaseException
? Does exception handling care about inheritance, etc, or does it only match the exact exception type being caught?
class MyException {
...
};
class MySpecialException : public MyException {
...
};
void test()
{
try {
...
}
catch (MyException &e) {
//will this catch MySpecialException?
}
}
If a class-based exception is not handled in a procedure, the system attempts to propagate it to the caller of the procedure. The exceptions that can be propagated from a procedure must be declared in its interface. The caller then knows which exceptions to expect from the procedure.
Exception Handling Using try-catch block When that statement is executed an exception is generated, which is caught by the catch block. The object of the type IndexOutOfRangeException is used to display a message to the user about the exception that has occurred.
Catching base and derived classes exceptions in C++To catch an exception for both base and derive class then we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.
In Object-Oriented Programming (OOP), exceptions are a powerful mechanism for centralized processing of errors and exceptional situations. This mechanism replaces the procedure-oriented method of error handling in which each function returns a code indicating an error or a successful execution.
It's easy to explain with code: http://ideone.com/5HLtZ
#include <iostream>
class ExceptionBase {
};
class MyException : public ExceptionBase {
};
int main()
{
try
{
throw MyException();
}
catch (MyException const& e) {
std::cout<<"catch 1"<<std::endl;
}
catch (ExceptionBase const& e) {
std::cout<<"should not catch 1"<<std::endl;
}
////////
try
{
throw MyException();
}
catch (ExceptionBase const& e) {
std::cout<<"catch 2"<<std::endl;
}
catch (...) {
std::cout<<"should not catch 2"<<std::endl;
}
return 0;
}
output:
catch 1
catch 2
C++ exception handling will match the exception subclasses. However, it performs a linear search from the first catch() to the last, and will only match the first one. So if you intend to catch both Base and Derived, you would need to catch(MySpecialException &) first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With