#include <iostream>
using namespace std;
int main()
{
int i;
char ch;
cout << "Please enter an integer and a character:\n";
try
{
cin >> i >> ch;
if (i == 0)throw 0;
if (ch == '!')throw '!';
}
catch (int)
{
cout << "'0' is an illegal integer." << endl;
}
catch (char)
{
cout << "'!' is an illegal character." << endl;
}
cout << "The end of the programming.";
}
结果分析:
①输入非零数,非!字符:The end of the programming.
②输入非零数,!:’!’ is an illegal character.
③输入0,任意字符:‘0’ is an illegal integer.
需注意:若输入0 !,并不会依次输出’!’ is an illegal character.”和“‘0’ is an illegal integer.两句,只会输出’0’ is an illegal integer.因为这是按照抛出表达式在此程序中的顺序进行的。一旦控制转移给句柄(即catch语句块),就不会自动返回。因此,即使输入0 !,也不会执行throw’!’,从而不会输出’!’ is an illegal character.