Exception Handling in C++ Programming Example (code)
Exceptions
Exceptions are the unexcepted outcomes that occur during the execution of the program that disturbs the program.
Types of Exceptions in C++
there are different types of exceptions in c++ some of them are given below.
- try-catch-throw
- multiple catches
- multiple try blocks
- catch-all
- user-defined exceptions
User-defined Exceptions
the exception that is inherited from the exception header file and coded by the user according to his requirements are called user-defined exceptions.
Example code of the user-defined exception
Program(code) Example
#include<iostream>#include<exception>using namespace std;class OverSpeed:public exception{ private: int speed; public: const char *what() { return "Speed Is exceeds Then Limit"; } void getSpeed() { cout<<"Speed of the Bike "<<speed<<endl; } void setSpeed(int speed) { this->speed=speed; }};class HeavyBike{ private: int speed; public: HeavyBike() { speed=0; cout<<"Speed of the Bike"<<speed<<endl; } void acceleration() { for(;;) { speed+=10; cout<<"Speed of bike is"<<speed<<endl; if(speed>=300){ OverSpeed s; s.setSpeed(speed); throw s; } } }};int main(){ HeavyBike Mehran; try{ Mehran.acceleration(); }catch(OverSpeed s) { cout<<s.what()<<endl; s.getSpeed(); } return 0;}
#include<iostream>