The main example here is copying a word document. I have these lines of code in my program:
try
{
File.Copy(docTemplatePath, docOutputPath, true);
}
catch (IOException e)
{
MessageBox.Show(e.ToString());
}
Now I’m trying to build in error checks. I want to make sure that the output Word Document is not open elsewhere before I try to save, because otherwise an exception is thrown.
The way I see it is that the exception is thrown to warn me of an error that is causing the default functionality of the code to not work as expected. In this sense I would feel comfortable catching an exception, reading it to discern the issue (in this case that the document is currently locked/open elsewhere) and thus showing a MessageBox to alert the user to the fact the document they’re trying to write to a file that is open elsewhere.
Is this fine to do? I have seen many places over the course of my looking into this where it would seem that this is what exceptions are designed to do, and other places where people seem to think thaat using exception to do stuff like this is hideously against all programming traditions and would prefer to check themselves.
What is the overall consensus?
Thanks
You should use Exceptions to handle exceptional occurrences.
That is; sometimes there will be foreseeable circumstances: A file name entered by a user might not exist, so your code should check
File.Exists()before attempting to load it, for example (not relying on an exception).That file already being in use and locked by something else might be an exceptional situation; it probably is, so that’s probably just fine.