尝试块在捕获后继续
Try block continues after catch
在重载的 operator[]
函数中,我有以下代码块:
try {
if (index < 0 || index >= n)
throw new std::out_of_range("Invalid index!");
return arr[index];
}
catch(std::out_of_range& ex) {
cout << ex.what() << endl;
}
函数调用方式
cout << arr[-1];
这会导致 未处理 std::out_of_range
异常。检查代码执行后发现,在throw
之后,并没有执行到catch
块,而是直接执行到return
语句。
我通常不会在同一个函数中捕获异常,这只是为了测试目的,我想了解发生了什么。
没有
throw new std::out_of_range("Invalid index!");
但是
throw std::out_of_range("Invalid index!");
为了在您的代码中详细说明,您正在捕获类型 std::out_of_range&
但抛出类型 std::out_of_range*
。正如评论中指出的那样,没有充分的理由不抓住 const std::out_of_range&
在重载的 operator[]
函数中,我有以下代码块:
try {
if (index < 0 || index >= n)
throw new std::out_of_range("Invalid index!");
return arr[index];
}
catch(std::out_of_range& ex) {
cout << ex.what() << endl;
}
函数调用方式
cout << arr[-1];
这会导致 未处理 std::out_of_range
异常。检查代码执行后发现,在throw
之后,并没有执行到catch
块,而是直接执行到return
语句。
我通常不会在同一个函数中捕获异常,这只是为了测试目的,我想了解发生了什么。
没有
throw new std::out_of_range("Invalid index!");
但是
throw std::out_of_range("Invalid index!");
为了在您的代码中详细说明,您正在捕获类型 std::out_of_range&
但抛出类型 std::out_of_range*
。正如评论中指出的那样,没有充分的理由不抓住 const std::out_of_range&