Catching an exception
suggest changeCode can and should throw exceptions in exceptional circumstances. Examples of this include:
- Attempting to read past the end of a stream
- Not having necessary permissions to access a file
- Attempting to perform an invalid operation, such as dividing by zero
- A timeout occurring when downloading a file from the internet
The caller can handle these exceptions by “catching” them, and should only do so when:
- It can actually resolve the exceptional circumstance or recover appropriately, or;
- It can provide additional context to the exception that would be useful if the exception needs to be re-thrown (re-thrown exceptions are caught by exception handlers further up the call stack)
It should be noted that choosing not to catch an exception is perfectly valid if the intention is for it to be handled at a higher level.
Catching an exception is done by wrapping the potentially-throwing code in a try { ... } block as follows, and catching the exceptions it’s able to handle in a catch (ExceptionType) { ... } block:
Console.Write("Please enter a filename: ");
string filename = Console.ReadLine();
Stream fileStream;
try
{
fileStream = File.Open(filename);
}
catch (FileNotFoundException)
{
Console.WriteLine("File '{0}' could not be found.", filename);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents