微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决发生错误时如何终止应用程序?

我正在使用一个名为 Irrlicht 的图形库 在某些时候,我必须编写此代码

    if(!device){
       //error code here`
   }

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

int main(){
   if(!device){
      return 1;
   }
return 0;
}

我不在主函数中,想退出函数之外的应用程序

解决方法

以下示例让您了解一些可能性。

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

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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。