在C ++中抛出超出范围的异常 [英] Throwing out of range exception in C++

查看:107
本文介绍了在C ++中抛出超出范围的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码适用;

int at(int index) {
  if(index < 1 || index >= size)
    throw 0;

  return x[index];
}

但这不

int at(int index) {
  if(index < 1 || index >= size)
    throw std::out_of_range;

  return x[index];
}



我得到错误期望的主表达式之前';'。现在...它让我惊讶,因为我知道std :: out_of_range存在,我有

I get the error "expected primary expression before ';'". Now... it surprises me because I know std::out_of_range exists and I have

#include <stdexcept>


推荐答案

替换 throw std :: out_of_range; 与 throw std :: out_of_range(blah); 。也就是说你需要创建一个对象,你不能抛出一个类型。

Replace throw std::out_of_range; with throw std::out_of_range ("blah");. I.e. you need to create an object, you cannot throw a type.

这篇关于在C ++中抛出超出范围的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆