While writing programs if the programmer doesn’t know what kind of exception the program might raise, the catch all block can be used. It is used to catch any kind of exception. Syntax of catch all block is as follows:
1 2 3 4 5 6 7 |
catch(...) { //Code to handle exception ... } |
While writing multiple catch statements care should be taken such that a catch all block should be written as a last block in the catch block sequence. If it is written first in the sequence, other catch blocks will never be executed. Following program demonstrates catch all block:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<iostream> using namespace std; int main() { int a, b; cout << "Enter a and b values: "; cin >> a >> b; try { if (b == 0) throw b; else if (b < 0) throw "b cannot be negative"; else cout << "Result of a/b = " << (a / b); } catch (int b) { cout << "b cannot be zero"; } catch (...) { cout << "Unkown exception in program"; } return 0; } |
Input and output for the above program is as follows:
1 2 3 4 |
Enter a and b values: 10 –5 Unkown exception in program |
Rethrowing an Exception
In C++ if a function or a nested try-block does not want to handle an exception, it can rethrow that exception to the function or the outer try-block to handle that exception. Syntax for rethrowing and exception is as follows:
throw;
Following program demonstrates rethrowing and exception to outer try-catch block:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<iostream> using namespace std; int main() { int a, b; cout << "Enter a and b values: "; cin >> a >> b; try { try { if (b == 0) throw b; else if (b < 0) throw "b cannot be negative"; else cout << "Result of a/b = " << (a / b); } catch (int b) { cout << "b cannot be zero"; } catch (...) { throw; } } catch (const char * msg) { cout << msg; } return 0; } |
Input and output for the above program is as follows:
1 2 3 4 |
Enter a and b values: 10 –2 b cannot be negative |
In the above program we can see that the exception is raised in the inner try block. The catch all block catches the exception and is rethrowing it to the outer try-catch block where it got handled.
Take your time to comment on this article.