Pages

July 24, 2010

keywords throw / try /catch and example of their usage

 void divide(int a[], int i, int n, int divisor) {
if(i <>= n)
throw "Outside array bounds";
else if(divisor == 0)
throw divisor;
else
a[i] = i / divisor;
}

int main() {
bool keepgoing = true;
int a[MAX] = {1,2,3,4,5,6,7,8,9,10}, index,
divisor;

do {
try {
cout << "Index: "; cin >> index;
cout << "Divisor: "; cin >> divisor;
divide(a, index, MAX, divisor);
cout << "a[index] = " << class="high">} catch(const char* msg) {

cout << keepgoing =" false;" class="high">} catch(int value) {
cout << "Zero divisor" << class="high">}
} while (keepgoing);

return 0;
}

All of the code within the try
block is executed repeatedly unless an exception is thrown by
any of the statements within the block. If an exception is
thrown, any remaining code within the try block is skipped and the code in the first
catch block that receives a type
matching the type of the thrown exception is executed. If
an exception is thrown and no match is found at any point in the
program, the program calls std::terminate(), which terminates
execution.


No comments:

Post a Comment