大家好,第一天来博客,希望一起学习进步

刚接触博客,希望能和大家一起学习进步。

今天刚刚学习了"异常"(exception)的一些情况。
主要是try和catch板块是使用,以及exception类的使用。
创建了一个vect类用来获取内存空间,在主函数中使用1000和100001来测试该类的exception情况。

#include <iostream>
#include "vect.h"
#include "vectexception.h"
using namespace std;

int main()
{
    try
    {
        vect(1000);
        cout << "Succeeded in the first time\n";
    }
    catch(vectexception &v)
    {
        cout << "Failed in the first time\n";
    }
    try
    {
        vect(100001);
        cout << "Succeeded in the second time\n";
    }
    catch(vectexception &v)
    {
        cout << "Failed in the second time\n";
    }
    return 0;
}

vect.h

#ifndef VECT_H_INCLUDED
#define VECT_H_INCLUDED
#include <iostream>
#include "vectexception.h"
class vect
{
    int *p;
public:
    vect(int n);
    vect();
    ~vect();
};

#endif // VECT_H_INCLUDED

vect.cpp

#include "vect.h"
using std::cout;
using std::endl;
vect::vect(int n)
{
    try
    {
        cout << "Try to get a block of memory:\n";
        if(n>100000)
        {
            throw vectexception();
        }
        p = new int[n];
        cout << "Got past the new request:\n";
    }
    catch(vectexception &v)
    {
        cout << "Caught the exception!\n";
        cout << v.what() << endl;
        throw v;
    }
}
vect::vect()
{
    p = new int[10];
}
vect::~vect()
{
    delete []p;
}

vectexception.h

#ifndef VECTEXCEPTION_H_INCLUDED
#define VECTEXCEPTION_H_INCLUDED
#include <exception>
using std::exception;
class vectexception:public exception
{
public:
    const char * what(){return "bad arguments to vectexception";}
};
#endif // VECTEXCEPTION_H_INCLUDED

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值