C++ Exception Handling
Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc. To handle the exception occur during program execution, the concept of exception handling is applied. Exception handling handles the exception occurs and transfer the program control to other parts of the program. Exception handling is used to detect and report an exception so that appropriate action can be taken. Exception handling follows the following steps to handle the exception:
- Find the exception (Hit the exception)
- Inform about exception occurrence (Throw the exception)
- Receive exception information (Catch the exception)
- Take proper action (Handle the exception)
- try
- throw
- catch
try{
.......
throw exception;
}
catch (type argument){
.......
.......
}
C++ Exception Handling Example 1
#include <iostream>
#include<string>
using namespace std;
int main () {
int n;
int d;
cout<< "Program to divide:\n";
cout<< "Enter numerator:\n";
cin>> n;
cout<< "Enter denominator:\n";
cin>> d;
try {
if( d == 0 ) {
throw "Division by zero condition!";
}
else{
cout<<"Result: "<<n/d;
}
}
catch (const char* msg) {
cout << msg << endl;
}
return 0;
}
Program to divide: Enter numerator: 6 Enter denominator: 2 Result: 3