close
Exceptions in C++ are implemented using three keywords that work in conjunction with each other: throw, try, and catch.
the first example :
int
main()
{
try
{
// Statements that may throw exceptions you want to handle now go here
throw
-1;
}
catch
(
int
)
{
// Any exceptions of type int thrown within the above try block get sent here
cerr <<
"We caught an exception of type int"
<< endl;
}
catch
(
double
)
{
// Any exceptions of type double thrown within the above try block get sent here
cerr <<
"We caught an exception of type double"
<< endl;
}
return
0;
}
the second example :
#include "math.h" // for sqrt() function
using
namespace
std;
int
main()
{
cout <<
"Enter a number: "
;
double
dX;
cin >> dX;
try
// Look for exceptions that occur within try block and route to attached catch block(s)
{
// If the user entered a negative number, this is an error condition
if
(dX < 0.0)
throw
"Can not take sqrt of negative number"
;
// throw exception of type char*
// Otherwise, print the answer
cout <<
"The sqrt of "
<< dX <<
" is "
<<
sqrt
(dX) << endl;
}
catch
(
char
* strException)
// catch exceptions of type char*
{
cerr <<
"Error: "
<< strException << endl;
}
}
ref : http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/
全站熱搜