Markus Doel
Markus Doel

Reputation: 23

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?

Upvotes: 2

Views: 175

Answers (3)

Karel Petranek
Karel Petranek

Reputation: 15164

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

Upvotes: 2

Mark B
Mark B

Reputation: 96311

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.

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46677

Because your're catching only exceptions of type int.

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

Upvotes: 7

Related Questions