问题
I am getting a FileNotFoundException while trying to execute a function with a try-catch block. I've tried catching a FileNotFoundException, to no avail. Can anyone tell me why it does this?
public static bool IsKeyValid(string path)
{
bool rVal = false;
try
{
Stream stream = File.Open(path + "\\data.bin", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
ValidKey vk = (ValidKey)bf.Deserialize(stream);
if (vk.SerialNumber != null)
rVal = true;
else
rVal = false;
}
catch (Exception fnfe)
{
rVal = false;
}
return rVal;
}
回答1:
My guess is that it's breaking into the FileNotFoundException
in the debugger when it's initially thrown, but that it would be correctly caught by the catch block. You can change the debugger settings for exceptions - or just run it outside the debugger, of course.
回答2:
The catch you have will catch all exceptions, but depending on how you have Visual Studio configured, it might still stop on the line raising the exception to give you a chance at debugging before the handler kicks in.
Go to the Debug|Exceptions
menu to control this.
来源:https://stackoverflow.com/questions/7423464/throwing-filenotfoundexception-but-not-catching