Try Catch Program in C++

This C++ program illustrate try-catch statement. The keyword try initiates a try-block in which statements can be executed. Then, the catch statement acts as a specifier of the type of exception to be caught if thrown from within the try-block. The compound-statement which follow the catch-statement is called the exception-handler and contains statements to be executed in response to the exception that was caught

Here is the source code of the C++ program which illustrate try-catch statement. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate try-catch Statement
  3.  */
  4. #include <iostream>
  5. #include <limits>
  6. using namespace std;
  7.  
  8. typedef numeric_limits<char> numlim;
  9. void to_char(int i)
  10. {
  11.     try
  12.     {
  13.         if (i < numlim::min() || i > numlim::max())
  14.             throw 1; // error code 1
  15.         else
  16.         {
  17.             cout << "The char value for " << i << " is \'"
  18.                  << static_cast<char>(i) << "\'" << endl;
  19.  
  20.             return;
  21.         }
  22.  
  23.     }
  24.     catch(int error)
  25.     {
  26.         // execute following if error == 1
  27.         if (error == 1)
  28.         {
  29.             cout << "Range Error : exceeding character limits"
  30.                  << endl;
  31.         }
  32.     }
  33. }
  34.  
  35. int main()
  36. {
  37.     int i;
  38.  
  39.     cout << "Enter a value ";
  40.     cin >> i;
  41.     to_char(i);
  42. }

$ a.out
Enter a value : 65
The char value for 65 is 'A'
$ a.out
Enter a value : 128
Range Error : exceeding character limits

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.