好吧,我试图理解和阅读可能导致它的原因,但我无法得到它:
我在我的代码中有这个地方:
try{
..
m.invoke(testObject);
..
} catch(AssertionError e){
...
} catch(Exception e){
..
}
Run Code Online (Sandbox Code Playgroud)
事实是,当它试图调用某个方法时,它会抛出
InvocationTargetException而不是其他预期的异常(具体而言ArrayIndexOutOfBoundsException).因为我实际上知道调用了什么方法,所以我直接使用了这个方法代码,并为假设要抛出的行添加了一个try-catch块 ArrayIndexOutOfBoundsException,它确实ArrayIndexOutOfBoundsException按预期抛出.然而,当它上升时它以某种方式改变,InvocationTargetException并且在上面的代码中,catch(Exception e)
e InvocationTargetException并不ArrayIndexOutOfBoundsException
像预期的那样.
什么可能导致这样的行为或我如何检查这样的事情?
我有这两个简单的功能.我认为这func1是一个很好的解决方案,因为你通过引用传递一个对象.我的教科书给出func2了最佳解决方案的答案.这只是因为你没有解除分配heapstr吗?如果我heapstr在main中声明然后将它传递给函数,那么我之后能够将其删除怎么办?
#include <iostream>
using namespace std;
string& func1(const string &str) {
string* heapstr=new string();
for (int i = 0; i < str.size(); ++i) {
*heapstr += str[i];
}
return *heapstr;
}
string func2(const string &str) {
string heapstr;
for (int i = 0; i < str.size(); ++i) {
heapstr += str[i];
}
return heapstr;
}
int main() {
cout << func1("aaa") << endl;
cout << func2("aaa") << endl;
}
Run Code Online (Sandbox Code Playgroud)