我正在使用一个名为Irrlicht的图形库,在某些情况下,我必须编写以下代码
if(!device){
//error code here`
}我不在主函数中,但当这个错误发生时,我想关闭应用程序,请记住,我是一个初学者,所以这个问题听起来可能很愚蠢,我看到一些人这样做:
int main(){
if(!device){
return 1;
}
return 0;
}我不在main函数中,希望在main函数之外退出应用程序
发布于 2021-07-11 15:15:57
下面的例子让你对其中的一些可能性有所了解。
您可以简单地复制和粘贴它,并使用它。只需使用一行“终止操作”,如throw或exit。如果在main函数中没有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;
}https://stackoverflow.com/questions/68333937
复制相似问题