Exception handling in C++ provides you with a way of handling unexpected circumstances like runtime errors. So whenever an unexpected circumstance occurs, the program control is transferred to special functions known as handlers. Show To catch the exceptions, you place some section of code under exception inspection. The section of code is placed within the try-catch block. If an exceptional situation occurs within that section of code, an exception will be thrown. Next, the exception handler will take over control of the program. In case no exceptional circumstance occurs, the code will execute normally. The handlers will be ignored. In this C++ tutorial, you will learn: Why Exception Handling?Here, are the reason for using Exception Handling in C++:
Exception Handling KeywordsException handling in C++ revolves around these three keywords:
Suppose a code block will raise an exception. The exception will be caught by a method using try and catch keywords. The try/catch block should surround code that may throw an exception. Such code is known as protected code. Syntax:The try/catch takes this syntax: try { // the protected code } catch( Exception_Name exception1 ) { // catch block } catch( Exception_Name exception2 ) { // catch block } catch( Exception_Name exceptionN ) { // catch block }
Example 1:#include<iostream> #include<vector> using namespace std; int main() { vector<int> vec; vec.push_back(0); vec.push_back(1); // access the third element, which doesn't exist try { vec.at(2); } catch (exception& ex) { cout << "Exception occurred!" << endl; } return 0; }Output: Here is a screenshot of the code: Code Explanation:
Example 2:#include <iostream> using namespace std; double zeroDivision(int x, int y) { if (y == 0) { throw "Division by Zero!"; } return (x / y); } int main() { int a = 11; int b = 0; double c = 0; try { c = zeroDivision(a, b); cout << c << endl; } catch (const char* message) { cerr << message << endl; } return 0; }Output: Here is a screenshot of the code: Code Explanation:
C++ Standard ExceptionsC++ comes with a list of standard exceptions defined in <exception> class. These are described below:
User-Defined ExceptionsThe C++ std::exception class allows us to define objects that can be thrown as exceptions. This class has been defined in the <exception> header. The class provides us with a virtual member function named what. This function returns a null-terminated character sequence of type char *. We can overwrite it in derived classes to have an exception description. Example:#include <iostream> #include <exception> using namespace std; class newException : public exception { virtual const char* what() const throw() { return "newException occurred"; } } newex; int main() { try { throw newex; } catch (exception& ex) { cout << ex.what() << '\n'; } return 0; }Output: Here is a screenshot of the code: Code Explanation:
Summary:
|