/* * Demonstrate how C++ handles exceptions * This code is written mostly in C style, except that it uses C++'s support for exceptions * Exceptions can be thrown and caught, just like in Java * Different exception types are identified by their data type (e.g. int vs string) * This program prompts the user to enter a number on the command line and * throws different exceptions in response to different errors. * Author: Ying Li */ #include //stdio.h in C int main (int argc, char *argv[]) { for (;;) { int q; try { printf("Enter a number (0..9): "); int k = scanf("%d", &q); // read formatted from stdin if (k == 0) { scanf("%*s"); //read the value but ignore throw "value is not a number"; } //this part is unnecessary, just show different types of exceptions if (q < 0) { throw 3.0; } if (q < 0 || q > 9) { throw q; } } catch (const char *s) { printf("Error: %s\n", s); continue; } catch (int v) { printf("Error: number %d is out of range (0..9)\n", v); continue; } catch (...) { printf("Unspecified error\n"); continue; } if (q == 0) break; } return 0; }