Building Custom or User Defined Exception Class




This video tutorial explains how to create a new user defined exception class by extending the exception base class in c++.
You are gonna learn how to inherit from the exception base class, how to override the " what " method in derived class, how to create an object from user defined exception class, how to define members in custom derived class, how to use the user defined exception type in your program in detail with example.

source code for this tutorial

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

class OverSpeed : public exception{
int speed;
public :
    const char* what(){
    return "check out ur car speed you are in the car not in the airoplane ";
    }
    void getSpeed(){
    cout <<"your car speed is "<< speed<<endl;
    }
   void setSpeed(int speed){
    this->speed = speed;
    }

};

class Car{
int speed;
public:
    Car(){
    speed = 0;
    cout << "speed is "<<speed<<endl;
    }

    void accelarate(){
    for(;;){
        speed += 10;
        cout << "speed is "<<speed<<endl;
        if(speed >= 250){
            OverSpeed s;
            s.setSpeed(speed);
            throw s;

        }
    }
    }

};

int main()
{
    Car anilscar;
    try{
    anilscar.accelarate();
    }catch(OverSpeed s){
    cout << s.what() <<endl;
    s.getSpeed();
    }

    return 0;
}

 
Back To Top