key word
- throw
- catch
- try
语法:
try
{
// protected code
}
catch (CMemoryException* e)
{
}
catch (CFileException* e)
{
}
catch (CException* e)
{
}
Catching Exceptions
try {
// protected code
}
catch (Exception e) {
// code to handle exceptionName exception
}
Demo
/*!
* \file hand_exception.cpp
* \date 2017/02/21 21:04
*
* \author henry
* Contact: henrytien@hotmail.com
*
* \brief
*
* TODO: long description
*
* \note
*/
#include <iostream>
using namespace std;
double division(int a, int b) {
if (b == 0) {
throw "Division is zero";
}
return a / b;
}
int main() {
int a = 12;
int b = 0;
double z = 0;
try {
z = division(a, b);
cout << z << endl;
}
catch (const char *msg) {
cerr << msg << endl;
}
system("pause");
return 0;
}
/*!
* \file cinexep.cpp
* \date 2017/02/21 21:08
*
* \author henry
* Contact: henrytien@hotmail.com
*
* \brief
*
* TODO: long description
*
* \note
*/
#include <iostream>
#include <exception>
using std::cout;
using std::cin;
using std::endl;
using namespace std;
int main() {
//have failbit cause an exception to be thrown
cin.exceptions(ios_base::failbit);
int sum = 0;
int input = 0;
cout << "Enter a number:";
try{
while (cin >> input) {
sum += input;
}
}catch (ios_base::failure &bf) {
cout << bf.what() << endl;
cout << "*_* " << endl;
}
cout << "last input entered=" << input << endl;
cout << "sum = " << sum << endl;
system("pause");
return 0;
}