当前位置:   article > 正文

C++ throw_c++中throw的用法

c++中throw的用法

我们知道C++ 异常处理的流程,具体为:

抛出(Throw)--> 检测(Try) --> 捕获(Catch)
  • 1

异常必须显式地抛出,才能被检测和捕获到;如果没有显式的抛出,即使有异常也检测不到。

在 C++ 中,我们使用 throw 关键字来显式地抛出异常,它的用法为:

throw exceptionData;
  • 1

exceptionData 是“异常数据”的意思,它可以包含任意的信息,完全有程序员决定。exceptionData 可以是 int、float、bool 等基本类型,也可以是指针、数组、字符串、结构体、类等聚合类型,请看下面的例子:

char str[] = "http://c.biancheng.net";
char *pstr = str;

class Base{
   };
Base obj;

throw 100;  //int 类型
throw str;  //数组类型
throw pstr;  //指针类型
throw obj;  //对象类型
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

一个动态数组的例子

C/C++ 规定,数组一旦定义后,它的长度就不能改变了;换句话说,数组容量不能动态地增大或者减小。这样的数组称为静态数组(Static array)。静态数组有时候会给编码代码不便,我们可以通过自定义的 Array 类来实现动态数组(Dynamic array)。所谓动态数组,是指数组容量能够在使用的过程中随时增大或减小。

使用异常示例。

#include <iostream>
#include <cstdlib>
using namespace std;

//自定义的异常类型
class OutOfRange{
   
public:
    OutOfRange(): m_flag(1){
    };
    OutOfRange(int len, int index): m_len(len), m_index(index), m_flag(2){
    }
public:
    void what() const;  //获取具体的错误信息
private:
    int m_flag;  //不同的flag表示不同的错误
    int m_len;  //当前数组的长度
    int m_index;  //当前使用的数组下标
};

void OutOfRange::what() const {
   
    if(m_flag == 1){
   
        cout<<"Error: empty array, no elements to pop."<<endl;
    }else if(m_flag == 2){
   
        cout<<"Error: out of range( array length "<<m_len<<", access index "<<m_index<<" )"<<endl;
    }else{
   
        cout<<"Unknown exception."<
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/714989
推荐阅读
  

闽ICP备14008679号