Tuesday, December 6, 2011

Working with Throwing and Catching Exceptions in console Application:

  • You can throw exceptions to indicate error conditions:
  1. An exception is an object that describes the error.
  2. All exception classes inherit from System.Exception.
  • To throw an exception:
  1. In Visual C#, use the throw keyword.
  • To catch an exception:
  1. In Visual C#, define try, catch, and finally blocks
Applications must be able to handle errors and exceptions in a uniform way. The CLR greatly assists the design of error-tolerant software by providing a platform that you can use to notify applications of errors in a consistent way. All .NET Framework methods indicate failure by throwing exceptions. An application can throw an exception when it encounters a condition outside its control. When the application throws an exception, the CLR searches the call tree for a catch handler that can handle that type of exception.
To throw an exception, use the throw (C#) keyword, followed by the exception object that you want to throw. The .NET Framework contains a large number of predefined exception classes that represent a wide range of common exceptions.

The following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter first number");
int i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number");
int j = Convert.ToInt32(Console.ReadLine());
int k = i / j;

}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.WriteLine("Finally block");
}
Console.WriteLine("Next line");
}
}
}

Output is display below:


Note: - The try block contains code that may throw an exception. When an exception is thrown in this block, the first catch block whose filter matches the class of the exception catches it. Note that the filter is specified as part of the catch clause.
• The catch block catches exceptions of a particular type. The exception object provides information about the error; for example, all exception objects have a Message property that describes the error.
• The finally block always executes regardless of whether an exception is thrown. The finally block performs clean-up operations such as closing database connections or closing windows.

1 comment:

Rasool Bevi said...

As a fresher, I learned much precious information about .net from your blog, Thanks for taking time to discuss about the beauty of dot net language.
Regards,
DOT NET Training in Chennai|DOT NET Course in Chennai

Recent Posts