当我试图在调用方法时捕捉异常时,我遇到了一个问题。
所以我有一个方法,在cpp文件中抛出异常:
char className::createSmth()
{
char l_char;
Type l_variable;
Type *pointer1 = l_variable.add_smth();
if (nullptr == pointer1)
{
throw std::runtime_error("pointer 1 is null");
}
else
{
Type *pointer 2 = pointer1->methodCall();
if (pointer)
{
//do smth;
}
else
{
throw std::runtime_error("pointer 2 is null");
}
}
return l_char;
}
我想在另一个方法中处理这些异常,并在catch块中再次抛出一个异常。
void className2::ExceptionsHandling(Type p_pointer)
{
Type *pointer3 = p_pointer->doSmth();
try
{
const Type l_localVariable = pointer3->createMessage();
}
catch(std::runtime error &e)
{
cout<< e.what()l
throw std::runtime_error("Throwing a exception to another method");
}
l_localVariable.Add(3);
}
但是我的编译器说:错误:“L_LocalVariable”未在此范围L_LocalVariable.add(3)中声明。
提前谢谢你!
try
块是一个单独的作用域,因此在try
块中声明的变量仅在那里可见。
您可以使用try
作用域中的对象:
try
{
const Type l_localVariable = pointer3->createMessage();
l_localVariable.Add(3);
}
catch(std::runtime error &e)
{
cout<< e.what();
throw std::runtime_error("Throwing a exception to another method");
}
或者(如果由于某种原因无法做到以上),您需要声明一个指针类型,该类型将在try
块中初始化:
std::unique_ptr<const Type> l_localVariable;
try
{
l_localVariable = std::make_unique(pointer3->createMessage());
}
catch(std::runtime error &e)
{
cout<< e.what();
throw std::runtime_error("Throwing a exception to another method");
}
l_localVariable->Add(3);