Exception Handling is a process to handle runtime errors.
It is required so that the normal flow of the application can be maintained even after runtime errors. In C++, an exception is an event or object which is thrown at runtime. All exceptions are derived from the std::exception class. It is a runtime error that can be handled. If we don’t handle the exception, it prints an exception message and terminates the program.
Standard exceptions are defined in the class that we can use inside our programs.
There are 3 keywords to perform exception handling:
- try
- catch, and
- throw
try block is used to place the code that may occur exception.
catch block is used to handle the exception.
Example Code using try/catch -
#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}catch (const char* e) {
cerr << e << endl;
}
return 0;
}
This will not throw an error and halt the program but show a user-defined error and continue the flow of the program.