Jon*_*nyK 6 c++ goto try-catch
我曾经被告知过的一切都是邪恶的,远离他们,但我认为他们可以帮助我(?).我想为用户提供一个选项,以便在发现异常时重新启动应用程序,并且在我要做什么事情时遇到一些麻烦...
我的应用程序将由另一个进程监视,但是有一些例外,我希望用户能够在不将控制权返回给调用进程的情况下决定做什么.
这样的事情是"可接受的"吗?还有其他建议吗?
非常感谢!
int main(){
initialize:
try{
//do things
}
catch(...)
{
cout<<"Would you like to try initializing again?"<<endl;
//if yes
goto initialize;
//if not
abort(); //or something...
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么不喜欢这个?
while(true){
//Do stuff
if(exit){
break;
}
}
Run Code Online (Sandbox Code Playgroud)
要么
continue = true;
do{
//Do stuff
if(exit){
continue = false;
}
}while(continue);
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以尝试:
int main()
{
while(true)
{
try
{
program();
}
catch(std::exception& e)
{
std::cout << "Start again?" << std::endl;
//Check ...
if(!go_on)
break;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是的,从技术上讲这是可以的,但通常的“转到被认为有害”的考虑因素适用。
一个goto可以随时被避免,给人干净的代码.
顺便说一下,break在a之外的情况也是如此switch.该continue关键字略微受到谴责,因为至少它尊重封闭循环的条件.
在正确的地方捕捉异常非常重要 - 您可以最有效地处理这种情况.
如果一个条件变得不方便(就像我的情况中的"再试一次?"),考虑否定它("失败?")以获得更清洁的结构.
// Tries until successful, or user interaction demands failure.
bool initialize() {
for ( ;; ) {
try {
// init code
return true;
}
catch ( ... ) {
cout << "Init Failed. Fail Program?" << endl;
if ( yes ) {
return false;
}
}
}
}
int main() {
if ( ! initialize() ) {
return EXIT_FAILURE;
}
// rest of program
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
注意:这不使用goto或break,并且它不会递归(特别是不在catch块内).
| 归档时间: |
|
| 查看次数: |
3446 次 |
| 最近记录: |