Catch unknown exception and print it in C++
This tutorial will focus on how to handle unknown exceptions and print that in C++.
We know that in programming there are many unknown exceptions that one should handle. Exception handling is very important for the smooth running of a program. If a programmer is not able to handle such exceptions then the program may halt.
Exception Handling in C++
- In C++, exception handling consists of three keywords try, throw and catch.
- In a try statement, it contains a block of code to be executed.
- Catch statement, the code is executed in a try block fails to execute.
- If a part of the code encounters a problem, we can throw the exception using the throw keyword.
Syntax for try/catch
try { // the desired code to be executed } catch( exceptionname e1 ) { // catch block } catch( exceptionname e2 ) { // catch block } catch( expname en ) { // catch block }
Here:
- Even though there is one try statement we can have multiple catch blocks.
- The “exception name” in the above syntax is the name of the exception.
- e1, e2, and en are the user-defined exception names pointing to these exceptions.
C++ codes for catching exceptions
Example 1:
#include <bits/stdc++.h> using namespace std; int main(){ //declare a vector vector<int> list; list.push_back(0); list.push_back(1); try { //accessing an element that is the out of bound list.at(2); } catch (exception& e) { //printing the error message cout << "error:index out of bound" << endl; } return 0; }
Output:
error: index out of bound
Example 2:
#include <bits/stdc++.h> using namespace std; double divide(int p, int q) { if (q == 0) { throw "error: Division by zero is undefined"; } return (p/q); } int main() { int x = 8 , y=0; double res = 0; try { res = divide(x, y); cout << res << endl; } catch (const char* e) { cerr << e << endl; } return 0; }
Output:
error: Division by zero is undefined
Hence, In this way, we can handle unknown exceptions and print them.
Leave a Reply