刚接触博客,希望能和大家一起学习进步。
今天刚刚学习了"异常"(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