In C++ if a functions or a nested try-blocks does not want to handle an exceptions, it can rethrow that exceptions to the functions or the outer try-block to handle that exceptions. Syntax for rethrowing and exceptions is as follow:
throw;
Following program demonstrate rethrowing and exceptions 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 ab, ba; cout << "Enter a and b value: "; cin >> ab >> ba; try { try { if (ba == 0) throw ba; else if (ba < 0) throw "ba cannot be negative"; else cout << "Result of ab/ba = " << (ab / ba); } catch (int ba) { cout << "ba cannot be zero"; } catch (...) { throw; } } catch (const char * msgs) { cout << msgs; } return 0; } |
Input and output for the above programsas 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 blocks where it got handled.
Throwing Exceptions in Function Definition
A function can declare what type of exception it might throw. Syntax for declaring the exceptions that a function throw is as follows:
1 2 3 4 5 6 7 |
return–type function–name(params–list) throw(type1, type2, ...) { //Function bodies ... } |
Following program demonstrate throwing exceptions in a function definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include<iostream> using namespace std; void sums() throw (int) { int ab, ba; cout << "Enter a and b values: "; cin >> ab >> ba; if (ab == 0 || ba == 0) throw 1; else cout << "Sum: " << (ab + ba); } int main() { try { sums(); } catch (int) { cout << "a or b cannot be zero"; } return 0; } |
Input and output for the above programs are as follows:
1 2 3 4 |
Enter ab and ba values: 5 0 an or b cannot be zero |
In the above programs, the sum() function can throw an exceptions of type int. So, the calling function must provides a catch block for the exception of type int.
Take your time to comment on this article.