Reputation: 2592
I have this code for saving to a file.
string filePath = Path.Combine(Path.GetTempPath(), "ConnectFour.txt");
try
{
using (StreamWriter myFile = File.CreateText(filePath))
{
// saving code
}
}catch (IOException){
MessageBox.Show("There was an error saving this game!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
} catch (Exception){
MessageBox.Show("There was an error saving this game!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
Is there a better way to handle exceptions when using file handling? maybe catch more specific exceptions like FileNotFound? What do you recommend? I'm asking this since when I am using my executable file for my application on another computer, I am getting the message box (an exception is being caught) and I can't know what it is! Also this exception isn't showing on each computer I have this application so it's more difficult to figure out!
Upvotes: 0
Views: 210
Reputation: 12205
As a general rule, you usually should not catch every exception (by writing catch(Exception)
), but only those, that you can really handle at this particular point.
Take a look at the documentation and see which exceptions can be thrown by all methods used in your saving code. Think about what they really mean in case of your specific algorithm and how you could translate the exceptions into user-friendly error messages.
For example, UnauthorizedAccessException and FileNotFoundException are very different things. The user does not understand what's wrong if you just write "An error occured".
Consider logging exceptions to get useful debugging information.
Upvotes: 1
Reputation: 62265
The exception based workflow management is a suggested guideline, if not the only possible, in case of dealing with IO
operations, so files too. Very often there is no other way to handle your program workflow, if not by expected exceptions handling when you're dealing with IO artifacts.
In your case, I would add catch
on all expected exceptions, and for others just will leave to go up to the stack.
Hope this helps.
Upvotes: 0
Reputation: 3071
You can do like this :
try{}
catch(exception ex){
if(ex is IOException){
messagebox.show("Your Specific Message");
//and do others like this
}
}
Upvotes: 0
Reputation: 4869
Why don't you use the exception that is thrown and show the Message:
}
catch( IOException e )
{
MessageBox.Show("There was an error saving this game: " + e.Message
, "ERROR"
, MessageBoxButtons.OK
, MessageBoxIcon.Exclamation
, MessageBoxDefaultButton.Button1);
}
And if the file must exist before your operation you could do a File.Exists( file )
.
Error checking is always prefered to exception handling...
Upvotes: 1