开发者

Exceptions in C++ problem

I have this code:

try
{
    files = Directory::GetFiles(path);
}catch(int){ 
    MessageBox::Show("Error getting files.");
    return 0; 
}

But when I run it and the GetFiles crashes, it still reports开发者_运维百科 unhandled exception. Why?


Because your're catching only exceptions of type int.

Use catch(...) to catch any kind of exceptions.


According to MSDN, GetFiles can throw the following exceptions:

IOException     
UnauthorizedAccessException     
ArgumentException   
ArgumentNullException   
PathTooLongException    
DirectoryNotFoundException

You do not catch any of them. The only exception you catch is of type int which cannot be thrown by GetFiles. To resolve the problem, either add catch statements for each of the exceptions above and handle them appropriately or use the ellipsis to catch all exceptions:

try {
  files = Directory::GetFiles(path);
} catch(...)  {
  MessageBox::Show("Error getting files.");
  return 0; 
}


I believe "Unhandled exception" is also used in Windows to mean memory protection error, and is not always the same thing as a C++ exception, which is what you're trying to catch here.

Possibly the path you're passing in has some garbage data in it. If the path is ok then you need to make sure you catch all the types of exceptions possibly thrown by your function, not just int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜