C++的异常捕获
2024-08-29 05:43:15
听课笔记:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std; void fun()
{
throw ;//抛出整型异常值
}
void fun02()
{
throw "hello!";//抛出const char* 类型的字符串
} class MyException
{
public:
MyException(const char* str)
{
cout << "构造函数被调用!" << endl;
error = new char[strlen(str) + ];
strcpy(error, str);
}
MyException(const MyException& ex)
{
cout << "拷贝构造函数被调用!" << endl;
error = new char[strlen(ex.error) + ];
strcpy(error, ex.error);
}
MyException operator=(const MyException& ex)
{
cout << "拷贝赋值函数被调用!" << endl;
if (error == ex.error)
{
return *this;
}
delete error;
error = new char[strlen(ex.error) + ];
strcpy(error,ex.error);
error = new char[strlen(ex.error) + ];
strcpy(error, ex.error);
return *this;
}
void what()
{
cout << "捕获异常: " <<error<< endl;
}
~MyException()
{
cout << "析构函数被调用!" << endl;
if (error!=NULL)
{
delete[] error;
} }
private:
char* error;
}; void fun03()
{ //创建一个临时对象,有的老师叫做匿名对象,这将要调用普通构造函数
throw MyException("wrong!");//既然可以抛内建数据类型的变量(对象),那也可以抛自定义类型的对象
} void test01()
{
try
{
fun();
}
catch (int e)//接收整型异常值,接收数据类型和抛出数据类型要匹配
{
cout << "捕获异常: " <<e<< endl;//打印catch到的异常值
}
try //try中放进去你认为可能出错的代码
{
fun02();
}
catch (const char* str1)//捕获异常,参数类型和抛出的数据类型要一致
{
cout << "捕获异常: " << str1 << endl;
}
try
{
fun03();
}
catch (MyException e)//抛出的是个自定义对象,捕获的参数类型也要是一个同类型的对象
{//接收抛出的对象相当于做对象拷贝,这要调用拷贝构造函数
e.what();
}
} int main()
{
test01();
system("pause");
return ;
}
最新文章
- Qt——浅谈样式表
- React-Native android在windows下的踩坑记
- .NET 扩展方法(Extention Method)的要点
- javascript实现九九乘法表
- 17.iOS App设置icon,启动图,App名称的方法
- JQuery实战手风琴-遁地龙卷风
- Reflector 反编译 .NET文件后修复
- iOS报错笔记
- Debian 入门安装与配置1
- Private Bytes,Working Set,Virtual Size的区别
- scanf()/getchar()和gets()深入分析
- Careercup - Facebook面试题 - 5110993575215104
- 【Android - MD】之TextInputLayout的使用
- [LeetCode] Range Sum Query - Mutable 题解
- java文件上传Demo
- Android 常见 Memory Leak 原因及解决办法总结
- django中request相关用法
- dubbo 序列化机制之 hessian2序列化实现原理分析
- org.apache.ibatis.binding.BindingException: Parameter &#39;start&#39; not found. Available parameters are [1, 0, param1, param2]
- COMS3200 The RUSH protocol
热门文章
- iOS collectionView添加类似tableView的tableHeaderView
- Swift迎来了1.0 GM 版(2014.09.09)
- Java 调用R 方法
- 如何开启Apache Rewrite功能
- 2017湘潭赛 A题 Determinant (高斯消元取模)
- MSP430G2553电子时钟实验
- mongodb 指南
- C#中Dictionary的作用及用法讲解
- 圆环自带动画进度条ColorfulRingProgressView
- EasyNVR无插件直播服务器软件使用详情功能-通道配置Excel