Exception Handling in C++
It is a mechanism to find and rectify the errors in a standard way. It uses some mechanisms to handle the exceptions.
It can be done by following ways.
Try catch : it is a block which searches the exception and thrown
it accordingly.
Throws: it also throws the exception.
Exception types:
It can be two types.
Based on logic errors
Based on runtime error
Let us create a c++ program to perform try-catch block.
Syntax:
‘try
{
} catch(Exception e) { }’
Code:
#include <iostream>
using namespace std;
int main() {
int num, den;
cout <<
"Enter the numerator value: ";
cin >> num;
cout <<
"Enter the denominator value: ";
cin >> den;
try {
if (den== 0) {
throw
"Division by zero is not allowed!";
}
cout <<
"The division value is: " << num / den << endl;
} catch (const
char* errorMsg) {
cout <<
"Error: " << errorMsg << endl;
}
return 0;
}
Output1:
Enter the numerator value: 56
Enter the denominator value: 7
The division value is: 8
Output:
Enter the numerator value: 64
Enter the denominator value: 0
ERROR!
Error: Division by zero is not allowed!
User defined Exception:
#include <iostream>
#include <exception>
using namespace std;
class sampleException : public exception {
public:
const char* what()
const noexcept override {
return "A
Custom exception is occurred!";
}
};
int main() {
try {
throw
sampleException();
} catch (const
sampleException& e) {
cout <<
e.what() << endl;
}
return 0;
}
Output:
A Custom exception is
occurred!
These are the two types of exception in C++ was explained briefly.
Hope, the blog is useful to you. Keep coding!!!
Comments
Post a Comment