Saturday, April 18, 2015

Briefly Explain About Exception Handling

Exceptions. 
All human endeavor has risk. Much like actions in our external reality, a computer's processes can fail. Nothing is safe.
It is awful. 
An error can occur at almost any statement. Checking for all these errors becomes unbearably complex. Exception handling separates this logic. It simplifies control flow.
However:It is best used only when needed—with the Tester-Doer pattern we keep exceptions exceptional.
Exceptional:
Grey areas exist. Exceptions are a high-level concept. What is exceptional depends on a program.
In programs, 
we can throw exceptions with a throw statement. But an exception is often thrown automatically by the runtime. An instruction may cause an invalid state.

Here:We divide by zero. Sadly this results in a DivideByZeroException. This operation cannot be continued.
Try:We use the try and catch blocks to structure our error handling. This may lead to cleaner code.
Based on:

.NET 4.5

C# program that throws an exception

using System;

class Program
{
    static void Main()
    {
 try
 {
     int value = 1 / int.Parse("0");
     Console.WriteLine(value);
 }
 catch (Exception ex)
 {
     Console.WriteLine(ex.Message);
 }
    }
}

Output

Attempted to divide by zero.

No comments:

Post a Comment