Alex Rivera | Logout

Throwing out of range exception in C++

Asked 2010-04-25T19:57:42.983
44

This code works;

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

  return x[index];
}

Yet this doesn't

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

  return x[index];
}

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>
Edit
Report

1 Answer

111

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.

answered 2010-04-25T20:01:25.487

Your Answer