Object Oriented Programming and C#: Exception Handling

Excepting handling is a way to anticipate errors during the code writing process. An exception is a runtime error  which happens when the program is executed. A “try” block is used to section off code that may cause an exception to occur. “Catch” blocks are used to handle these exceptions. A “finally” block will run regardless of whether an exception is triggered from the “try” block. A “try” block can be implemented along with a “catch” block, both a “catch” and “finally” block, or just a “finally” block.

In the following code, an equation is coded to divide by zero, prompting an error. The suspect code is encased within the “try” block.

exception

The Exception class is used to generate the error message (“Error is: Attempting to divide by zero”). When the code below is run (with the value of x changed), no error message is displayed, but the code within the “finally” block is run regardless of any condition. If x is changed back to zero, the same error message appears.

morecode