Code can and should throw exceptions in exceptional circumstances. Examples of this include:
The caller can handle these exceptions by "catching" them, and should only do so when:
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);
}