关于C++的实用异常研究
1. 简单输出自己设定的提示信息
(1)问题描述
在异常抛出领域,刚开始很难记得清楚都要抛出什么错误,不如就简单的抛出一下自己设定的提示语句,也就是说执行到某一句如果出错,简单抛出提示语句,继续执行后边的内容。
(2)代码部分
这里简单用了几个文件分开写了一下。
circle.h
#ifndef CALCULATEFUN_TIME_CIRCLE_H
#define CALCULATEFUN_TIME_CIRCLE_H
# include <iostream>
void sayHello(int num);
#endif //CALCULATEFUN_TIME_CIRCLE_H
circle.cpp
# include "circle.h"
void sayHello(int num){
for (int i = 0; i < num; ++i) {
std::cout << "hello world" << std::endl;
}
throw "hello, here is the try-catch strure";
}
main.cpp
#include <iostream>
#include <sysinfoapi.h>
#include "circle.h"
int main() {
unsigned long time_1 = 0, time_2 = 0;
time_1 = GetTickCount(); // calculate the start time
try{
sayHello(2);
}catch (const char * str){
std::cout<< str << std::endl; // try-catch test
}
time_2 = GetTickCount(); // calculate the end time
std::cout<< (time_2 - time_1) << std::endl;
return 0;
}
(3)运行结果
(4)代码分析
注意,这里我加了一个计算函数运行时间的函数 GetTickCount(),单位以ms计算。