Search code examples
c++irrlicht

How to terminate an application when an error happnes?


I am using a Graphics Library called Irrlicht at some point i have to write this code

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

i am not in the main function but want to close the application when this error happens please keep in mind that I am a beginner so this question might sound dumb i see some people do this:

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

i am not in the main function and want to exit the application outside of the main function


Solution

  • The following example give you an idea about some of the possibilities.

    You can simply copy and paste it and play around with it. Simply use only one line of the "termination actions" like throw or exit. If you don't have the try catch block in the main function, your application will also terminate because the exception will not be caught.

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