Sunday, April 19, 2015

Why We Use Finally For Managing Errors and Exception

Finally :
C# Support Another Statement Known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statement , finally block can be used to handle any exception generated within a try block . It may be be added immediately after the last catch block shown as follows :
try                                                                                                      
{
  ...........
  ...........
}
finally
{
............
 ............
}

another example :

try                                                                                                      
{
  ...........
  ...........
}
catch(.........)
{
  ...........
  ..........
}
catch(.........)
{
  ...........
  ..........
}
finally
{
 ............
 ............
}

When a finally block is defined , this is guaranteed to execute , regardless of whether or not in exception is thrown , As a result , we can use it to perform certain house - keeping operation such as closing files and releasing system resource . 

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.