Errors
If the method doesn't throw an exception, no error occurred. The method was able to perform the job it promised it would do, so it will get out of the way, and won't try to return some sort of status code. You won't need to check a status code because you will know that it has succeeded.
If the method fails the copy operation, an exception will be thrown. In this case the method wasn't able to perform the job it promised it would do, which means something weird (exceptional) happened, so an exception gets thrown. Since an exception is thrown, you are forced to deal with it, or your program blows up. So there is no point in checking for a status code. You couldn't write any code that would be able to read that status code anyhow, since the status checking code would never be reached. Code flow would go to the catch
block, or to program termination.
These concepts are the basis of error handling using exceptions.
How to handle exceptions
Unless you need to, and have some reasonable way to recover from the exception, then don't handle them. Let your program blow up. This will make it much easier to find bugs in your code out in the wild, since an unhandled exception will produce a stack trace, which will tell you exactly which part of your program blew up, and how the code got to that point.
If you have a reasonable way to recover (e.g. simply display an error message to the user and retry the operation, or let them input a different parameter), then you can write a try
/catch
block. Write your code that could throw an exception in the try
block, and write your recovery code in the catch
block.
try
{
var file = File.Open(filename);
// Todo: Work with open file here
}
catch(FileNotFoundException e)
{
MessageBox.Show("Failed to open file - " + e.ToString());
// Todo: Additional recovery here,
// like telling the calling code to re-open the file selection dialog
}
Note that you should never catch the base Exception
type, and instead should catch the specific derived exception types that you can handle (e.g. FileNotFoundException
). This makes sense because you probably can't write code that will successfully recover from an OutOfMemoryException
, and that exception could get thrown at any point in your code. If you catch Exception
, then you are writing code that tries to handle anything, not just the exceptions you are interested in.
Completion
File.Copy
is a synchronous operation. So once the method has completed, then the actual copy has completed.
This means that you can write a line of code immediately after the copy line. And that code can expect the file to be there, for it to be fully copied, and for it to be accessible.