70-536 exam: General Exception Handling
14 March 2010
.Net exception handling follows generic computer science principles:
In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. Depending on the situation, the handler may later resume the execution at the original location using the saved information. For example, a page fault will usually allow the program to be resumed, while a division by zero might not be resolvable transparently.
Source: Wikipedia
public static void Main()
{
try
{
// Code that could throw an exception
}
catch(System.Net.WebException exp)
{
// Process a WebException
}
catch(System.Exception)
{
// Process a System level CLR exception, that is not a System.Net.WebException,
// since the exception has not been given an identifier it cannot be referenced
}
catch
{
// Process a non-CLR exception
}
finally
{
// (optional) code that will *always* execute
}
}
Source: Wikipedia
Namespace: System Assembly: Mscorlib (in Mscorlib.dll)
Here the control passes to the ArithmeticException handler (and not the more generic Exception handler)
int x = 0;
try { int y = 100/x;}
catch (ArithmeticException e)
{Console.WriteLine("ArithmeticException Handler: {0}", e.ToString());}
catch (Exception e)
{Console.WriteLine("Generic Exception Handler: {0}", e.ToString());}
run this code returns a DivideByZeroException via the ArithmeticException handler
ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero at ConsoleApplication1.Program.Main() in C:\Users\[path]\Program.cs:line 16
Source: Microsoft
If you liked this blog post, you may want to subscribe to my news feed in your RSS reader.
