C# .NET - what is exception handling and what is use of exception handling

Asked By prasanna venaktesan
28-Aug-08 12:20 AM
end of post

See this  See this

28-Aug-08 12:34 AM

Exception Handling:

"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION INA CODE SEQUENCE. " In C# Exception is a class in the system namespace. An object of an exception is that describe the exceptional conditions occur in a code That means, we are catching an exception, creating an object of it, and then throwing it. C# supports exceptions in a very much the same way as Java and C++.

Use Of Exception Handling:

Trapping and handling of runtime errors is one of the most crucial tasks ahead of any programmer. But, before discussing runtime errors, let's look at compile time errors, which are errors that occur during compilation time. They may be due to bad coding, misspelling of syntaxes, and so on. They can be corrected by studying the error messages and warnings the compiler produces.

On the other hand, runtime errors occur at the time the program executes and can't be corrected. A programmer can, however, take preventive measures while coding the program. To do so, a programmer should first identify these two aspects:

  • Find out the part or parts of a program that are most likely to emit runtime errors.
  • Handle those errors according to language conventions.

C# provides an elegant way to handle runtime errors with the help of the try, catch, and finally keywords. Before moving ahead, let's consider a situation where the exception is not handled. We will explain the concept with the help of a "Division by Zero" example.

The general form try-catch-finally in C# is shown below  

try
{
// Statement which can cause an exception.
}
catch
(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

Example;

class  With
{
  public static void Main()
  {
    try
    {
      int x = 5;
      int y = 0;
      int z = x/y;
      Console.WriteLine(z);
    }
    catch(DivideByZeroException e)
    {
      Console.WriteLine("Error occurred, unable to compute");
    }
  }
}
Go thr these links;
http://www.c-sharpcorner.com/UploadFile/rajeshvs/ExceptionHandlinginCSharp11282005051444AM/ExceptionHandlinginCSharp.aspx
http://www.codeguru.com/csharp/csharp/cs_syntax/anandctutorials/article.php/c5859
Best Luck!!!!!!!!!!!!!!
Sujit.

exception handling  exception handling

28-Aug-08 12:35 AM

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.

go to this link

http://support.microsoft.com/kb/315965

Exception Handling in Asp.net  Exception Handling in Asp.net

28-Aug-08 12:37 AM

See these articles ::

http://www.codeguru.com/csharp/.net/net_asp/miscellaneous/article.php/c12385 (Good One)

http://www.eggheadcafe.com/articles/20030816.asp (Good one)

http://www.codegod.de/webappcodegod/Exception-handling-in-ASP-NET-AID375.aspx

http://www.theserverside.net/discussions/thread.tss?thread_id=23444

Hope it helps.

Read this  Read this
28-Aug-08 12:42 AM

Base Class Exception Classes

This section provides a quick survey of some of the exceptions available in the .NET base class library. Microsoft has provided a large number of exception classes in .NET - too many to provide a comprehensive

 
All the classes are part of the System namespace, with the exception of IOException and the classes derived from IOException, which are part of the namespace System.IO. The System.IO namespace deals with reading and writing data to files. In general, there is no specific namespace for exceptions. Exception classes should be placed in whatever namespace is appropriate to the classes that can generate them - hence IO-related exceptions are in the System.IO namespace, and you will find exception classes in quite a few of the base class namespaces.

The generic exception class, System.Exception, is derived from System.Object, as you would expect for a .NET class. In general, you should not throw generic System.Exception objects in your code, because they provide no specifics about the error condition.

Two important classes in the hierarchy are derived from System.Exception:

  • System.SystemException - This class is for exceptions that are usually thrown by the .NET runtime or that are considered to be of a generic nature and might be thrown by almost any application. For example, StackOverflowException will be thrown by the .NET runtime if it detects the stack is full. On the other hand, you might choose to throw ArgumentException or its subclasses in your own code, if you detect that a method has been called with inappropriate arguments. Subclasses of System.SystemException include classes that represent both fatal and nonfatal errors.

  • System.ApplicationException - This class is important, because it is the intended base for any class of exception defined by third parties. Hence, if you define any exceptions covering error conditions unique to your application, you should derive these directly or indirectly from System.ApplicationException.

Other exception classes that might come in handy include the following:

  • StackOverflowException - This exception is thrown when the area of memory allocated to the stack is full. A stack overflow can occur if a method continuously calls itself recursively. This is generally a fatal error, because it prevents your application from doing anything apart from terminating (in which case it is unlikely that even the finally block will execute). Trying to handle errors like this yourself is usually pointless and instead you should get the application to gracefully exit.

  • OverflowException - An OverflowException is what happens if you attempt to cast an int containing a value of -40 to a uint in a checked context.

The class hierarchy for exceptions is somewhat unusual in that most of these classes do not add any functionality to their respective base classes. However, in the case of exception handling, the common reason for adding inherited classes is to indicate more specific error conditions, and there is often no need to override methods or add any new ones (although it is not uncommon to add extra properties that carry extra information about the error condition). For example, you might have a base ArgumentException class intended for method calls where inappropriate values are passed in, and an ArgumentNullException class derived from it, which is intended to handle a null argument if passed.

Catching Exceptions

Given that the .NET Framework includes a spate of predefined base class exception objects, how do you use them in your code to trap error conditions? In order to deal with possible error conditions in C# code, you will normally divide the relevant part of your program into blocks of three different types:

  • try blocks encapsulate the code that forms part of the normal operation of your program and that might encounter some serious error conditions.

  • catch blocks encapsulate the code that deals with the various error conditions that your code might have encountered by working through any of the code in the accompanying try block. This place could also be used for logging errors.

  • finally blocks encapsulate the code that cleans up any resources or takes any other action that you will normally want done at the end of a try or catch block. It is important to understand that the finally block is executed whether or not an exception is thrown. Because the aim is that the finally block contains cleanup code that should always be executed, the compiler will flag an error if you place a return statement inside a finally block. For an example of using the finally block, you might close any connections that were opened in the try block. It is also important to understand that the finally block is completely optional. If you don’t have a requirement for any cleanup code (such as disposing or closing any open objects), then there is no need for this block.

So how do these blocks fit together to trap error conditions? Here’s how:

  1. The execution flow first enters the try block.

  2. If no errors occur in the try block, execution proceeds normally through the block, and when the end of the try block is reached, the flow of execution jumps to the finally block if one is present (Step 5). However, if an error does occur within the try block, execution jumps to a catch block (next step).

  3. The error condition is handled in the catch block.

  4. At the end of the catch block, execution automatically transfers to the finally block if one is present.

  5. The finally block is executed (if present).

The C# syntax used to bring all this about looks roughly like this:


try
{
   // code for normal execution
}
catch
{
   // error handling
}
finally
{
   // clean up
}

Actually, a few variations on this theme exist:

  • You can omit the finally block because it is optional.

  • You can also supply as many catch blocks as you want to handle specific types of errors. However, the idea is that you shouldn’t get too carried away and have a huge number of catch blocks, as this can hurt the performance of your application.

  • You can omit the catch blocks altogether, in which case the syntax serves not to identify exceptions, but as a way of guaranteeing that code in the finally block will be executed when execution leaves the try block. This is useful if the try block contains several exit points.

So far so good, but the question that has yet to be answered is this: If the code is running in the try block, how does it know when to switch to the catch block if an error has occurred? If an error is detected, the code does something known as throwing an exception. In other words, it instantiates an exception object class and throws it:


throw new OverflowException();

Here, you have instantiated an exception object of the OverflowException class. As soon as the computer encounters a throw statement inside a try block, it immediately looks for the catch block associated with that try block. If there is more than one catch block associated with the try block, it identifies the correct catch block by checking which exception class the catch block is associated with. For example, when the OverflowException object is thrown, execution jumps to the following catch block:


catch (OverflowException ex)
{
   // exception handling here
}

In other words, the computer looks for the catch block that indicates a matching exception class instance of the same class (or of a base class).

With this extra information, you can expand the try block just demonstrated. Assume, for the sake of argument, that there are two possible serious errors that can occur in the try block: an overflow and an array out of bounds. Assume that your code contains two Boolean variables, Overflow and OutOfBounds, which indicate whether these conditions exist. You have already seen that a predefined exception class exists to indicate overflow (OverflowException); similarly, an IndexOutOfRangeException class exists to handle an array that is out of bounds.

Now your try block looks like this:


try
{
   // code for normal execution
   if (Overflow == true)
  {
      throw new OverflowException();
   }

   // more processing

   if (OutOfBounds == true)
   {
      throw new IndexOutOfRangeException();
   }

   // otherwise continue normal execution
}
catch (OverflowException ex)
{
   // error handling for the overflow error condition
}
catch (IndexOutOfRangeException ex)
{
   // error handling for the index out of range error condition
}
finally
{
   // clean up
}

So far, this might not look that much different from what you could have done with the Visual Basic 6 On Error GoTo statement (with the exception perhaps that the different parts in the code are separated). C#, however, provides a far more powerful and flexible mechanism for error handling.

This is because you can have throw statements that are nested in several method calls inside the try block, but the same try block continues to apply even as execution flow enters these other methods. If the computer encounters a throw statement, it immediately goes back up through all the method calls on the stack, looking for the end of the containing try block and the start of the appropriate catch block. During this process, all the local variables in the intermediate method calls will correctly go out of scope. This makes the try...catch architecture well suited to the situation described at the beginning of this section, where the error occurs inside a method call that is nested inside 15 or 20 method calls, and processing has to stop immediately.

As you can probably gather from this discussion, try blocks can play a very significant part in controlling the flow of execution of your code. However, it is important to understand that exceptions are intended for exceptional conditions, hence their name. You wouldn’t want to use them as a way of controlling when to exit a do...while loop.

Implementing Multiple Catch Blocks

The easiest way to see how try...catch...finally blocks work in practice is with a couple of examples. The first example is called SimpleExceptions. It repeatedly asks the user to type in a number and then displays it. However, for the sake of this example, imagine that the number has to be between 0 and 5; otherwise, the program won’t be able to process the number properly. Therefore, you will throw an exception if the user types in anything outside of this range.

The program then continues to ask for more numbers for processing until the user simply presses the Enter key without entering anything.

Tip 

You should note that this code does not provide a good example of when to use exception handling. As already indicated, the idea of exceptions is that they are provided for exceptional circumstances. Users are always typing in silly things, so this situation doesn’t really count. Normally, your program will handle incorrect user input by performing an instant check and asking the user to retype the input if there is a problem. However, generating exceptional situations is difficult in a small example that you can read through in a few minutes! So, we will tolerate this bad practice for now in order to demonstrate how exceptions work. The examples that follow present more realistic situations.

The code for SimpleExceptions looks like this:


using System;

namespace Wrox.ProCSharp.AdvancedCSharp
{
   public class MainEntryPoint
   {
      public static void Main()
      {
         string userInput;
         while (true)
         {
            try
            {
               Console.Write("Input a number between 0 and 5 " +
                  "(or just hit return to exit)> ");
               userInput = Console.ReadLine();

               if (userInput == "")
               {
                  break;
               }

               int index = Convert.ToInt32(userInput);

               if (index < 0 || index > 5)
               {
                  throw new IndexOutOfRangeException(
                     "You typed in " + userInput);
               }

               Console.WriteLine("Your number was " + index);
            }
            catch (IndexOutOfRangeException ex)
            {
               Console.WriteLine("Exception: " +
                  "Number should be between 0 and 5. {0}", ex.Message);
            }
            catch (Exception ex)
            {
               Console.WriteLine(
                 "An exception was thrown. Message was: {0}", ex.Message);
            }
            catch
            {
               Console.WriteLine("Some other exception has occurred");
            }
            finally
            {
               Console.WriteLine("Thank you");
            }
         }
      }
   }
}

The core of this code is a while loop, which continually uses Console.ReadLine() to ask for user input. ReadLine() returns a string, so your first task is to convert it to an int using the System.Convert .ToInt32() method. The System.Convert class contains various useful methods to perform data conversions and provides an alternative to the int.Parse() method. In general, System.Convert contains methods to perform various type conversions. Recall that the C# compiler resolves int to instances of the System.Int32 base class.

Tip 

It is also worth pointing out that the parameter passed to the catch block is scoped to that catch block - which is why you are able to use the same parameter name, ex, in successive catch blocks in the preceding code.

In the preceding example, you also check for an empty string, because this is your condition for exiting the while loop. Notice how the break statement actually breaks right out of the enclosing try block as well as the while loop because this is valid behavior. Of course, once execution breaks out of the try block, the Console.WriteLine() statement in the finally block is executed. Although you just display a greeting here, more commonly, you will be doing tasks like closing file handles and calling the Dispose() method of various objects in order to perform any cleaning up. Once the computer leaves the finally block, it simply carries on executing unto the next statement that it would have executed had the finally block not been present. In the case of this example, though, you iterate back to the start of the while loop, and enter the try block once again (unless the finally block was entered as a result of executing the break statement in the while loop, in which case you simply exit the while loop).

Next, you check for your exception condition:

if (index < 0 || index > 5)
{
   throw new IndexOutOfRangeException("You typed in " + userInput);
}

When throwing an exception, you need to choose what type of exception to throw. Although the class System.Exception is available, it is only intended as a base class. It is considered bad programming practice to throw an instance of this class as an exception, because it conveys no information about the nature of the error condition. Instead, the .NET Framework contains many other exception classes that are derived from System.Exception. Each of these matches a particular type of exception condition, and you are free to define your own ones as well. The idea is that you give as much information as possible about the particular exception condition by throwing an instance of a class that matches the particular error condition. In the preceding example, System.IndexOutOfRangeException is the best choice in the circumstances. IndexOutOfRangeException has several constructor overloads. The one chosen in the example takes a string, which describes the error. Alternatively, you might choose to derive your own custom Exception object that describes the error condition in the context of your application.

Suppose that the user then types a number that is not between 0 and 5. This will be picked up by the if statement and an IndexOutOfRangeException object will be instantiated and thrown. At this point, the computer will immediately exit the try block and hunt for a catch block that handles IndexOutOfRangeException. The first catch block it encounters is this:

catch (IndexOutOfRangeException ex)
{
   Console.WriteLine(
      "Exception: Number should be between 0 and 5. {0}", ex.Message);
}

Because this catch block takes a parameter of the appropriate class, the catch block will be passed the exception instance and executed. In this case, you display an error message and the Exception.Message property (which corresponds to the string you passed to the IndexOutOfRange’s constructor). After executing this catch block, control then switches to the finally block, just as if no exception had occurred.

Notice that in the example, you have also provided another catch block:

catch (Exception ex)
{
   Console.WriteLine("An exception was thrown. Message was: {0}", ex.Message);
}

This catch block would also be capable of handling an IndexOutOfRangeException if it weren’t for the fact that such exceptions will already have been caught by the previous catch block. A reference to a base class can also refer to any instances of classes derived from it, and all exceptions are derived from System.Exception. So why isn’t this catch block executed? The answer is that the computer executes only the first suitable catch block it finds from the list of available catch blocks. So why is this second catch block even here? Well, it is not only your code that is covered by the try block. Inside the block, you actually make three separate calls to methods in the System namespace (Console.ReadLine(), Console.Write(), and Convert.ToInt32()), and any of these methods might throw an exception.

If you type in something that’s not a number - say a or hello - the Convert.ToInt32() method will throw an exception of the class System.FormatException to indicate that the string passed into ToInt32() is not in a format that can be converted to an int. When this happens, the computer will trace back through the method calls, looking for a handler that can handle this exception. Your first catch block (the one that takes an IndexOutOfRangeException) won’t do. The computer then looks at the second catch block. This one will do because FormatException is derived from Exception, so a FormatException instance can be passed in as a parameter here.

The structure of the example is actually fairly typical of a situation with multiple catch blocks. You start off with catch blocks that are designed to trap very specific error conditions. Then, you finish with more general blocks that will cover any errors for which you have not written specific error handlers. Indeed, the order of the catch blocks is important. If you had written the previous two blocks in the opposite order, the code would not have compiled, because the second catch block is unreachable (the Exception catch block would catch all exceptions). Therefore, the uppermost catch blocks should be the most granular options available and ending with the most general options.

However, in the previous example, you have a third catch block listed in the code:

catch
{
   Console.WriteLine("Some other exception has occurred");
}

This is the most general catch block of all - it doesn’t take any parameter. The reason this catch block is here is to catch exceptions thrown by other code that isn’t written in C# or isn’t even managed code at all. You see, it is a requirement of the C# language that only instances of classes derived from System .Exception can be thrown as exceptions, but other languages might not have this restriction - C++, for example, allows any variable whatsoever to be thrown as an exception. If your code calls into libraries or assemblies that have been written in other languages, it might find that an exception has been thrown that is not derived from System.Exception, although in many cases, the .NET PInvoke mechanism will trap these exceptions and convert them into .NET Exception objects. However, there is not that much that this catch block can do, because you have no idea what class the exception might represent.

Tip 

For this particular example, there is no point in adding this catch-all catch handler. Doing this is useful if you are calling into some other libraries that are not .NET-aware and that might throw exceptions. However, it is included it in the example to illustrate the principle.

Now that you have analyzed the code for the example, you can run it. The following output illustrates what happens with different inputs and demonstrates both the IndexOutOfRangeException and the FormatException being thrown:

SimpleExceptions
Input a number between 0 and 5 (or just hit return to exit)> 4
Your number was 4
Thank you
Input a number between 0 and 5 (or just hit return to exit)> 0
Your number was 0
Thank you
Input a number between 0 and 5 (or just hit return to exit)> 10
Exception: Number should be between 0 and 5. You typed in 10
Thank you
Input a number between 0 and 5 (or just hit return to exit)> hello
An exception was thrown. Message was: Input string was not in a correct format.
Thank you
Input a number between 0 and 5 (or just hit return to exit)>
Thank you
You can't debug a problem if you don't know that it exists thats why we use exception handling  You can't debug a problem if you don't know that it exists thats why we use exception handling
28-Aug-08 01:11 AM

A great way to do this is to implement an exception handler at the application level. This will allow you to consolidate the logging and notification parts of your exception handling in one convenient place. As you'll see from the code examples that follow, your global exception handler can handle both specific exceptions that you trap in your code and generic unhandled exceptions.

your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page

you declare an Exception object and initialize it through a call to Server.GetLastError().GetBaseException().

The GetLastError() method of the Server object simply returns a reference to a generic HttpException. This is a wrapper that was placed around the original exception when it was passed from your ASP.NET page to the Application_Error event. To get access to the original exception, you need to call its GetBaseException() method. This will yield the original exception information, regardless of how many layers have been added to the exception tree

Often the best way to deal with exceptions is to not handle them at all. If you can let them pass through your code and allow destructors to handle cleanup, your code will be cleaner.

Issue...  Issue...
28-Aug-08 01:32 AM

We dont know what error occured at runtime. That error can be Divide by zero, SQL connection timeout error etc. So, we need to do exception handling.

C# Supports try - catch - finally block to handle exception.

e.g.

 

try

{

   //Code here

}

catch (SqlException sqlexc)

{

     Response.write(sqlexc.Message);

}

catch (Exception exc)

{

     Response.write(exc.Message);

}

finally

{

      //Always execute code which is written here 

}
Actually, there are 2 types of exceptions.
1)   User Defined Exception
2)   System Defined Exception
reply  reply
28-Aug-08 01:34 AM
C# language uses many types of exceptions, which are defined in special classes. All of them are inherited from base class named System.Exception.
There are classes that process many kinds of exceptions: out of memory exception, stack overflow exception, null reference exception, index out of range exception, invalid cast exception, arithmetic exception etc
. The most important are try, catch and finally

   The first one to be known is the try operator. This is used in a part of code, where there exists a possibility of exception to be thrown. But operator ?try? is always used with the operators: catch and finally

  See the following example of handling a simple exception in c#.

//Sample code for C# Exception tutorial using try , catch

// try catch exception
int zero = 0;
try
{
    int div = 100/zero;
}
catch(DivideByZeroException)
{
    Console.WriteLine("Division by zero exception passed");
}

This code in runtime throws a DivideByZeroException and writes some message through the console. But if you want to release some resources that were created you must use try ? finally construction. Finally will be called even if there were no exceptions raised.


go through this link which will giv u the complte idea of exception handling:

http://www.codersource.net/csharp_tutorial_exceptions.html

http://www.devarticles.com/c/a/C-Sharp/Exception-Handling-in-C-sharp/




check this  check this
28-Aug-08 01:38 AM

A sad reality associated with being human is that we are all error prone. Because software is a human creation, it often suffers from this same weakness.

Hence, we are required to have Exception handling to handle the unknown or sometimes known errors and continue our further process in the application..

Please do check this which clearl;y explains in detail..

http://docs.rinet.ru/JavDev/ch22.htm

nothing other than this  nothing other than this
02-Sep-08 03:25 AM

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. 

C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below  

try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. 

But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. 

If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto. 

In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc. 

Uncaught Exceptions 

The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program. 

//C#: Exception Handling
//Author: rajeshvs@msn.com
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 100/x;
Console.WriteLine(div);
}


The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero. 

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("This line
in not executed");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
Console.WriteLine("Result is {0}",div);
}


In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.
If a finally block is present, the code inside the finally block will get also be executed.  

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}


Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}


But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block.

Multiple Catch Blocks 

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error. 

//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}


Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.  

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}


The following program handles all exception with Exception object. 

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(Exception e)
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}


Throwing an Exception 

In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows. 

throw exception_obj;

For example the following statement throw an ArgumentException explicitly. 

throw new ArgumentException("Exception");

//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}


Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this.  

//C#: Exception Handling: Handling all exceptions
using System;
class MyClass
{
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc =
new MyClass();
try
{
mc.Method();
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Standard Exceptions

There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.

The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.

  • System.OutOfMemoryException
  • System.NullReferenceException
  • Syste.InvalidCastException
  • Syste.ArrayTypeMismatchException
  • System.IndexOutOfRangeException        
  • System.ArithmeticException
  • System.DevideByZeroException
  • System.OverFlowException 

User-defined Exceptions

In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes. 

//C#: Exception Handling: User defined exceptions
using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
Console.WriteLine("LAST STATEMENT");
}
}

Design Guidelines

Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected, such as reaching the end of a file. If there's a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message. Finally, if code catches an exception that it isn't going to handle, consider whether it should wrap that exception with additional information before re-throwing it.

Create New Account
help
it. ArgumentOutOfRangeException - Argument value is out of range. ArithmeticException - Arithmetic over - or underflow has occurred. ArrayTypeMismatchException - Attempt to store the wrong type of object in an array. BadImageFormatException - Image is in the wrong format. CoreException - Base class for exceptions thrown by the runtime. DivideByZeroException - An attempt was made to divide by zero. FormatException - The format of an argument is wrong. IndexOutOfRangeException - An array index is out of bounds. InvalidCastExpression - An attempt was made to cast to WriteLine( "My program starts" ) ; try { a = 10 / b; } catch ( InvalidOperationException e ) { Console.WriteLine ( e ) ; } catch ( DivideByZeroException e) { Console.WriteLine ( e ) ; } finally { Console.WriteLine ( "finally" ) ; } Console.WriteLine ( "Remaining program" ) ; The output here
System.AppDomainSetup System.AppDomainUnloadedException System.ApplicationException System.ArgumentException System.ArgumentNullException System.ArgumentOutOfRangeException System.ArithmeticException System.ArrayTypeMismatchException System.BadImageFormatException System.CannotUnloadAppDomainException System.Collections.ArrayList System.Collections.CaseInsensitiveComparer System.Collections.CaseInsensitiveHashCodeProvider System.Collections Diagnostics.StackTrace System.Diagnostics.SymbolStore.SymDocumentType System.Diagnostics.SymbolStore.SymLanguageType System.Diagnostics.SymbolStore.SymLanguageVendor System.DivideByZeroException System.DllNotFoundException System.DuplicateWaitObjectException System.EnterpriseServices.CompensatingResourceManager.ClerkMonitor System.EnterpriseServices.CompensatingResourceManager.Compensator System.EnterpriseServices.Internal Globalization.KoreanCalendar System.Globalization.NumberFormatInfo System.Globalization.StringInfo System.Globalization.TaiwanCalendar System.Globalization.ThaiBuddhistCalendar System.IndexOutOfRangeException System.InvalidCastException System.InvalidOperationException System.InvalidProgramException System.IO.DirectoryNotFoundException System.IO.DriveNotFoundException System.IO.EndOfStreamException
mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero. / / C#: Exception Handling / / Author: rajeshvs@msn int div = 0; try { div = 100 / x; Console.WriteLine(“This line in not executed”); } catch(DivideByZeroException de) { Console.WriteLine("Exception occured"); } Console.WriteLine("Result is {0}", div); } } In the above case x = 0; int div = 0; try { div = 100 / x; Console.WriteLine("Not executed line"); } catch(DivideByZeroException de) { Console.WriteLine("Exception occured"); } finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is {0 x = 0; int div = 0; try { div = 100 / x; Console.WriteLine("Not executed line"); } catch(DivideByZeroException de) { Console.WriteLine("DivideByZeroException" ); } catch(Exception ee) { Console.WriteLine("Exception" ); } finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is Author: rajeshvs@msn.com using System; class MyClient { public static void Main() { try { throw new DivideByZeroException("Invalid Division"); } catch(DivideByZeroException e) { Console.WriteLine("Exception" ); } Console.WriteLine("LAST STATEMENT"); } } Re-throwing an Exception The exceptions, which System; class MyClass { public void Method() { try { int x = 0; int sum = 100 / x; } catch(DivideByZeroException e) { throw; } } } class MyClient { public static void Main() { MyClass mc = new MyClass(); try { mc.Method
System.IndexOutOfRangeException was unhandled System.IndexOutOfRangeException was unhandled Message = "An SqlParameter with ParameterName '@txtProductType' is not contained by this SqlParameterCollection." is db.GetParameterValue(command, "txtProductType" )); please help ramm Hi Yes exception message giving full details. System.IndexOutOfRangeException was unhandled Message = " An SqlParameter with ParameterName '@txtProductType' is not contained by this SqlParameterCollection ." It