News
IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Jan 18 2015 5:28AM     Mohammad Shaik
  0 Comments    1548 Views  
Here Mohammad Shaik provided a short tutorial with example, about Exception Handling in C#.
What is Exception Handling ?
  1. An exception is a problem that arises during the execution of a program.
  2. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
  3. Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw.
Built in Keywords:
  • try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
  • catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
  • finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
  • throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Before going into detail, I must say the usefulness of knowing and performing exception handling :
  1. They cannot be ignored, as if calling code does not handle the error, it causes program termination.
  2. They do not need to be to be handled at the point where error took place. This makes them very suitable for library or system code, which can signal an error and leave us to handle it.
  3. They can be used when passing back a return value cannot be used.
Exceptions are handled by using try...catch statements.
Exceptions is enclosed in a try block, which is followed by one or more catch blocks. Well if you don't use try...catch, you could get errors like the following:
Syntax
Assuming a block will raise and exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   // statements causing exception
}
catch( ExceptionName EN1 )
{
   // Error handling code
}
catch( ExceptionName EN2 )
{
   // Error handling code
}
catch( ExceptionName EN3 )
{
   // Error handling code
}
finally
{
   // Statements to be executed
}

Example:

int a, b = 0 ;
Console.WriteLine( "My First Application" ) ;
try

a = 10 / b;
}
catch ( Exception ex )
{
Console.WriteLine ( ex ) ;
}
Console.WriteLine ( "Remaining program" ) ;

My program starts
System.DivideByZeroException: Attempted to divide by zero. at ConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c#(c sharp)\swapna\programs\consoleapplication4\ consoleapplication4\class1.cs:line 51
Remaining program
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception ClassDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.
Example:

int a, b = 0 ;
Console.WriteLine( "My First Application" ) ;
try
{
a = 10 / b;
}
catch ( InvalidOperationException e )
{
Console.WriteLine ( e ) ;
}
catch ( DivideByZeroException e)
{
Console.WriteLine ( e ) ;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;

My program starts
System.DivideByZeroException: Attempted to divide by zero. at ConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c# (c sharp)\swapna\programs\consoleapplication4\ consoleapplication4\class1.cs:line 51 finally
Remaining program
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this:

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: ApplicationException
{
   public TempIsZeroException(string message): base(message)
   {
   }
}
public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}

When the above code is compiled and executed, it produces the following result:
div id="Div14" class="codeBG contentColor">

TempIsZeroException: Zero Temperature found

Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as:

Catch(Exception e)
{
   ...
   Throw e
}

I hope this page will helps to learn Exception Handling in C#. Thanks.
BackToTop
Comments



 
Search
Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Nov 21 2017 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Nov 8 2017 10:26AM Posted By Pranav
Google URL Shortener in C#
Oct 26 2017 10:43AM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Jun 18 2017 11:38PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Feb 27 2017 11:51AM Posted By John
Gridview custom CSS in ASP.Net
Feb 25 2017 10:59AM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Feb 25 2017 10:20AM Posted By Micheal
Tags
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: