C++笔记 第六十四课 C++中的异常处理(上)---狄泰学院

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42187898/article/details/84650569

如果在阅读过程中发现有错误,望评论指正,希望大家一起学习,一起进步。
学习C++编译环境:Linux

第六十四课 C++中的异常处理(上)

1.C++异常处理

C++内置了异常处理的语法元素try…catch…
try语句处理正常代码逻辑
catch语句处理异常情况
try语句中的异常由对应的catch语句处理
在这里插入图片描述
C++通过throw语句抛出异常信息
在这里插入图片描述
C++异常处理分析
throw抛出的异常必须被catch处理
当前函数能够处理异常,程序继续往下执行
当前函数无法处理异常,则函数停止执行,并返回
未被处理的异常会顺着函数调用栈向上传播,直到被处理为止,否则程序将停止执行。
在这里插入图片描述

64-1 C++异常处理初探

#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b)
{
    const double delta = 0.000000000001;
    double ret = 0;
    if( !((-delta < b) && ( b < delta)))
    {
	ret = a / b;
    }
    else
    {
	throw 0;
    }
    return ret;
}
int main(int argc, char *argv[])
{
    try
    {
    double r = divide(1,0);
    cout << "r = "<< r << endl;
    }
    catch(...)
    {
	cout << "Divided by zero..." << endl;
    }
    
    return 0;
}
运行结果
Divided by zero...

同一个try语句可以跟上多个catch语句
catch语句可以定义具体处理的异常类型
不同类型的异常由不同的catch语句负责处理
try语句中可以抛出任何类型的异常
catch(…)用于处理所有类型的异常
任何异常都只能被捕获(catch)一次
异常处理的匹配规则
在这里插入图片描述

64-2 异常类型匹配

#include <iostream>
#include <string>
using namespace std;
void Demo1()
{
    try
    {
	throw 1;
    }
    catch(char c)
    {
	cout << "catch(char c) " << endl;
    }
    catch(short c)
    {
	cout << "catch(short c) " << endl;
    }
    catch(double c)
    {
	cout << "catch(double c) " << endl;
    }
    catch(int c)
    {
	cout << "catch(int c) " << endl;
    }
    catch(...)
    {
	cout << "catch(...) " << endl;
    }
}
void Demo2()
{
    throw "YLC";
}
int main(int argc, char *argv[])
{
    Demo1();
    try
    {
        Demo2();
    }
    catch(char* s)
    {
	cout << "catch(char *s)" << endl;
    }
    catch(const char* cs)
    {
	cout << "catch(const char* cs)" << endl;
    }
    catch(string ss)
    {
	cout << "catch(string ss)" << endl;
    }
    return 0;
}
运行结果
catch(int c) 
catch(const char* cs)

小结
C++中直接支持异常处理的概念
try…catch…是C++中异常处理的专用语句
try语句处理正常代码逻辑,catch语句处理异常情况
同一个try语句可以跟上多个catch语句
异常处理必须严格匹配,不进行任何的类型转换

猜你喜欢

转载自blog.csdn.net/weixin_42187898/article/details/84650569