如果数组索引超出范围,则尝试抛出范围错误C++

问题描述

如果我的函数访问的数组索引越界,我试图让我的程序抛出一个 std::range_error。传入的类型是size_t,因为堆栈中的内存位置可能是有符号的,也可能是无符号的。

这是我尝试过的:

MyClass::MyClass(){ // default constr
    size = 10;
    ptr = new int[size];
} 

int MyClass::at(size_t position) const
{
    try
    {
        return ptr[pos];
    }
    catch (const std::range_error&)
    {
        cout << "Range Error" << endl;
    }   
}

int main() {
    // Test exceptions
    MyClass a;
    throw_(a.at(0),range_error);
}

任何人都可以帮助更正我的函数,以便在索引超出范围时抛出 range_error 吗?

解决方法

您的班级应该始终知道数组的大小。您可以立即知道传递的值是否超出范围并抛出。

您的 log4j-slf4j-impl 无法工作。 <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <classpathDependencyExcludes> <classpathDependencyExclude>org.apache.logging.log4j:log4j-slf4j-impl</classpathDependencyExclude> </classpathDependencyExcludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <configuration> <classpathDependencyExcludes> <classpathDependencyExclude>org.apache.logging.log4j:log4j-slf4j-impl</classpathDependencyExclude> </classpathDependencyExcludes> </configuration> </plugin> </plugins> </build> 不会抛出。它的作用就像一个简单的内存偏移。

您的函数应该更像这样:

try