C++实用异常

关于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计算。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值