C++ Exception Handling


In C++ Exception Handling is a process to handle runtime errors.

Exception handling consists of three keywords: try, catch, and throw.

  • Throw - when a program throws an exception using a throw keyword.
  • Catch - The catch keyword helps to the catching of an exception.
  • Try - A try block is used to place the code that might generate an exception. It's followed by one or more catch blocks.
C++ exception

Syntax:

try {
   // try block
} catch( Exception e ) {
   // catch block
}

Exception Description
std::exception This exception is parent class of all the standard C++ exceptions.
std::runtime_error An exception that cannot be detected by reading the code.
std::logic_failure An exception that can be detected by reading a code.
std::bad_alloc An exception is thrown by new.
std::bad_exception An exception is handle the unexpected exceptions.
std::bad_cast An exception is thrown by dynamic_cast.
std::bad_typeid An exception is thrown by typeid
std::overflow_error An exception is thrown if a mathematical overflow occurs.
std::range_error This exception occurred when you try to store a value which is out of range.

Example:

#include <iostream>
using namespace std;

class A{
    public:
    double division(int a, int b) 
    {
       if( b == 0 ) 
       {
          throw "Divide by zero is not possible!";
       }
       return (a/b);
    }
};
int main () {
    A a;
    int z;
    try {
        z=a.division(1, 0);
        cout << z << endl;
    } 
    catch (const char* e) {
        cerr << e << endl;
    }
    return 0;
}

User-Defined Exceptions

User-Defined Exceptions is the process of creating your own exceptions by inheriting and overriding exception class functionality.


Example:

#include <iostream> 
#include <exception> 
using namespace std;  

class MyException : public exception{  
    public:  
        const char * what() const throw()  
        {  
            return "User-Defined Exceptions !";  
        }  
};  
int main()  
{  
    try  
    {  
        throw MyException();
    }  
    catch(exception& e)  
    {  
        cout << e.what();  
    }  
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.