有可以處理這幾種不同的方式。
把一個function-try-block身體周圍的main()
:
int main() try
{
A a;
// use 'a' as needed ...
return EXIT_SUCCESS;
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
重構代碼,以大量的main()
移動到另一個函數,您可以再try/except
塊內撥打:
void run()
{
A a;
// use 'a' as needed ...
}
int main()
{
try
{
run();
return EXIT_SUCCESS;
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
}
個人,我只是在堆上而不是在堆上實例化類。這樣,你可以把try/catch
只是實例:
#include <memory>
int main()
{
std::unique_ptr<A> a; // or std::auto_ptr<A> prior to C++11...
try
{
a.reset(new A);
// or, in C++14 and later:
// a = std::make_unique<A>();
}
catch(const std::exception& e)
{
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
// use 'a' as needed ...
// the A object is freed automatically when 'a' goes out of scope...
return EXIT_SUCCESS;
}
「如果這主要是數千行長?」這將是你的問題,而不是try/catch塊。 –
圍繞這種類型的代碼可能會失敗(並且不能被其他方式阻止),而不是整個事情。您不需要依靠巨大的try/catch來處理您的項目中可能發生的任何錯誤,這也可以捕獲意外的異常。 –
[main()返回int] try-catch塊在main中是一個(接近普遍的)常見做法。 「......數千行......」是惡毒的。 – Loreto