C++ 如何抓住c++;内置异常对象

C++ 如何抓住c++;内置异常对象,c++,C++,当我调用一个方法时,当我试图捕获异常时,我遇到了一个问题 所以我有一种方法,在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 *po

当我调用一个方法时,当我试图捕获异常时,我遇到了一个问题

所以我有一种方法,在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);
}
void className2::异常处理(键入p\u指针)
{
键入*pointer3=p_指针->doSmth();
尝试
{
常量类型l_localVariable=pointer3->createMessage();
}
捕获(标准::运行时错误&e)
{

cout
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");
}

是的,
l\u localVariable
try
块的本地变量,因此不能在外部使用它。只需在外部声明它。您必须使其非常量,但这可能是您想要的,因为您正在对其调用
Add
,这似乎是一个修改操作。请参见,在以下代码序列中:
…cout
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);