C++ TUTORIALS - C++ Exception Handling
C++ Exception Handling
ADVERTISEMENTS
C++ Standard Exceptions:
Exception | Description |
---|---|
std::exception | An exception and parent class of all the standard C++ exceptions. |
std::bad_alloc | This can be thrown by new. |
std::bad_cast | This can be thrown by dynamic_cast. |
std::bad_exception | This is useful device to handle unexpected exceptions in a C++ program |
std::bad_typeid | This can be thrown by typeid. |
std::logic_error | An exception that theoretically can be detected by reading the code. |
std::domain_error | This is an exception thrown when a mathematically invalid domain is used |
std::invalid_argument | This is thrown due to invalid arguments. |
std::length_error | This is thrown when a too big std::string is created |
std::out_of_range | This can be thrown by the at method from for example a std::vector and std::bitset<>::operator[](). |
std::runtime_error | An exception that theoretically can not be detected by reading the code. |
std::overflow_error | This is thrown if a mathematical overflow occurs. |
std::range_error | This is occured when you try to store a value which is out of range. |
std::underflow_error | This is thrown if a mathematical underflow occurs. |
ADVERTISEMENTS
try { // protected code }catch( ExceptionName e1 ) { // catch block }catch( ExceptionName e2 ) { // catch block }catch( ExceptionName eN ) { // catch block }ADVERTISEMENTSThrowing Exceptions:
double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); }Catching Exceptions:
try { // protected code }catch( ExceptionName e ) { // code to handle ExceptionName exception }
try { // protected code }catch(...) { // code to handle any exception }
#include <iostream> using namespace std; double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; }catch (const char* msg) { cerr << msg << endl; } return 0; }Define New Exceptions:
#include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; int main() { try { throw MyException(); } catch(MyException& e) { std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { //Other errors } }