Exception handling allows you to handle an event in a manner that does something about the exception or shuts down an application gracefully.
To use exception handling, you must place the code that you want to guard against an exception in a try block:
try
{
//Code to be guarded
}
After you have the code to be guarded identified, you need to write a block of code that will handle the exception:
catch(exception type)
{
//Handle the event
}
You can also use what is called a default exception handler, catch(…), to catch all exceptions, but this is not advisable. You should have some idea of the type of exceptions that could occur in your code. In most cases, catching all exceptions is not best practice, because it allows you to not be concerned with the exact exceptions being thrown. You should always try to catch the most specific exceptions that you can.
Another approach to ensure that code will be executed prior to shutting down the application is to use the finally keyword. The finally keyword will be executed immediately after the catch block is executed. If a catch block is not present, the finally keyword will execute after the try block completes or an exception is thrown in the try block.
The throw statement is used to force an exception of a specified type.
throw new MyException("My Exception has been thrown!");
The following example demonstrates exception handling with try/catch, finally, and throw.
using System;
using System.IO;
namespace Client.Chapter_9___Exception Handling_and_Application Domains
{
class MyMainClass
{
delegate int MyDelegate(string s);
static void Main(string[] args)
{
StreamWriter MyStream = null;
string MyString = "Hello World";
//Creates a guarded code block
try
{
MyStream = File.CreateText("MyFile.txt");
MyStream.Write(MyString);
}
//Catches IOException
catch (IOException e)
{
Console.WriteLine(e);
}
//Catches generic exceptions
catch (Exception e)
{
Console.WriteLine(e);
}
//Guarded code block that is guaranteed to be executed
finally
{
if (MyStream != null)
MyStream.Close();
}
}
}
public class MyFile
{
public StreamWriter WriteText(string s)
{
if (!Valid(s))
//Throws an exception
throw new IOException("Can't Write String");
else
return new StreamWriter("c:\\test.txt");
}
public bool Valid(string s)
{
return false;
}
}