throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
catch: 在您想要处理问题的地方,通过异常处理程序捕获异常。catch 关键字用于捕获异常。
try: try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。
抛出一个异常:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
由于除法除以零是不合法的,因此抛出一个异常。
实例测试:
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
抛出的异常是const char*类型的,因此接收一场的时候也要是const char*类型的
输出:Division by zero condition!
另外,cree和cout的区别:
cout的输出可以重定向到一个文件中,而cerr必须输出在显示器上。
cout是标准输出流,与cerr的区别在于cerr不经过缓冲区,直接向显示器输出信息,而cout中的信息存放在缓冲区,缓冲区满或者遇到endl时才输出。
实例测试为:
扫描二维码关注公众号,回复:
10895841 查看本文章
#include <iostream.h>
int main()
{
cout << "hello world---cout" << endl ;
cerr << "hello world---cerr" << endl ;
return 0;
}
输出为:
hello world --cout
hello world --cerr