首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当发生错误时如何终止应用程序?

当发生错误时如何终止应用程序?
EN

Stack Overflow用户
提问于 2021-07-11 15:00:47
回答 1查看 61关注 0票数 0

我正在使用一个名为Irrlicht的图形库,在某些情况下,我必须编写以下代码

代码语言:javascript
复制
    if(!device){
       //error code here`
   }

我不在主函数中,但当这个错误发生时,我想关闭应用程序,请记住,我是一个初学者,所以这个问题听起来可能很愚蠢,我看到一些人这样做:

代码语言:javascript
复制
int main(){
   if(!device){
      return 1;
   }
return 0;
}

我不在main函数中,希望在main函数之外退出应用程序

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-11 15:15:57

下面的例子让你对其中的一些可能性有所了解。

您可以简单地复制和粘贴它,并使用它。只需使用一行“终止操作”,如throwexit。如果在main函数中没有try catch block,您的应用程序也将终止,因为将不会捕获异常。

代码语言:javascript
复制
struct DeviceNotAvailable {}; 
struct SomeOtherError{};

void func()
{
    void* device = nullptr; // only for debug

    if (!device)
    {   
// use only ONE of the following lines:
        throw( DeviceNotAvailable{} );
        //throw( SomeOtherError{} );
        //abort();
        //exit(-1);
    }   
}

int main()
{
    // if you remove the try and catch, your app will terminate if you
    // throw somewhere
    try 
    {   
        func();
    }   
    catch(DeviceNotAvailable)
    {   
        std::cerr << "No device available" << std::endl;
    }   
    catch(SomeOtherError)
    {   
        std::cerr << "Some other error" << std::endl;
    }   

    std::cout << "normal termination" << std::endl;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68333937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档