Exception Example


A common exception is dividing by zero. Exceptions are generally linked to an action. For dividing by zero, the action is a divisor of zero. Integer division, where the divisor is zero, triggers a divide by zero exception. (However, floating-point division by zero does not cause an exception; instead, infinity is returned.) The following code causes an unhandled divide by zero exception, which terminates the application:

 using System; namespace Donis.CSharpBook{     public class Starter{         public static void Main(){             int var1=5, var2=0;             var1/=var2;    // exception occurs         }     } } 

Place code that is likely to raise an exception in a try block because code in a try block is protected from exceptions. Exceptions raised in the try block are trapped. The stack is then walked by the CLR, searching for the appropriate exception handler. Code not residing in a try block is unprotected from exceptions. In this circumstance, the exception eventually evolves into an unhandled exception. As demonstrated in the previous code, an unhandled exception is apt to abort an application.

In the following code, the divide by zero exception is caught in a try block. Trapping, catching, and handling an exception are separate tasks. The catch statement consists of a catch filter and block. The DivideByZeroException filter catches the divide by zero exception. The catch block handles the exception, which is to display the stack trace. The proximity of the infraction is included in the stack trace. Execution then continues at the first statement after the catch block.

 using System; namespace Donis.CSharpBook{     public class Starter{         public static void Main(){             try {                 int var1=5, var2=0;                 var1/=var2;    // exception occurs             }             catch(DivideByZeroException except) {                 Console.WriteLine("Exception "+except.StackTrace);             }         }     } } 




Programming Microsoft Visual C# 2005(c) The Language
Microsoft Visual Basic 2005 BASICS
ISBN: 0619267208
EAN: 2147483647
Year: 2007
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net