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.
/*
* C++ Program to Illustrate try-catch Statement
*/
#include <iostream>
#include <limits>
using namespace std;
typedef numeric_limits<char> numlim;
void to_char(int i)
{
try
{
if (i < numlim::min() || i > numlim::max())
throw 1; // error code 1
else
{
cout << "The char value for " << i << " is \'"
<< static_cast<char>(i) << "\'" << endl;
return;
}
}
catch(int error)
{
// execute following if error == 1
if (error == 1)
{
cout << "Range Error : exceeding character limits"
<< endl;
}
}
}
int main()
{
int i;
cout << "Enter a value ";
cin >> i;
to_char(i);
}
$ 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]Related Posts:
- Apply for C++ Internship
- Check Programming Books
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Computer Science Books