Translate

Wednesday, September 5, 2012

Exception Handling in .Net or Handling Exception in C#

Exception Handling or Handling Exception

What is an Exception

An exception is an indication of an error or exceptional condition such as when try to open a file that is not physically exists or when we write a method which throws exception, the calling code must be able to detect and handle exception.
If the calling method code cannot handle the exception, the exception is automatically propagated to the code that invoked the calling code.

The exception is propagated until a section of code handles the occurred exception.
If no code handles the exception, there are 100 percent chances that it will give runtime errors and will report unhandled exception and finally the application will crash.

How Exceptions Propagate in .Net Framework

This is where exceptions in the .NET Framework prove useful. An exception is an indication of an error or exceptional condition. A method can throw an exception when it detects that something unexpected has happened, for example, it tries to open a file, but the file does not exist. When a method throws an exception, the calling code must be prepared to detect and handle this exception. If the calling code does not detect the exception, it is aborted and the exception is automatically propagated to the code that invoked the calling code. This process continues until a section of code takes responsibility for handling the exception. Execution continues in this section of code after the exception-handling logic has completed.

For an example, suppose the ABC method calls the DEF method. As part of its processing,the DEF method calls the GH method. While it is running, the GH method throws an exception. This exception may cause the GH method to abort, and the exception is passed back to the DEF method. If the DEF method is not prepared to handle the exception, it also aborts and the same exception is passed back to the ABC method. If the ABC method handles the exception, execution continues in the ABC method after the exception-handling logic. If the ABC method is not prepared to handle the exception, the exception will be propagated back to the method that called the ABC method. If this is the Main method, and Main is also not prepared to handle the exception, the application reports the unhandled exception to the user and then terminates.
ABC method can catch and handle its own exceptions to provide a degree of robustness that the calling code may not even be aware of. For example, a method that updates a database may catch an exception that occurs if the connection to the database fails. It may try connecting again, possibly with an alternative set of credentials. This process can be hidden from the code that called the method.

Using Try and Catch in C#

try/catch block is the plays a key role in programming. We wrap the code that may fail and cause an exception in a try block, and add one or more catch blocks to handle any exceptions that may occur.

The following example shows about how to implement Try Catch

try
{
// Try block.
}
catch ([catch specification 1])
{
// Catch block 1.
}
catch ([catch specification 2])
{
// Catch block 2.
}
catch ([catch specification 3])
{
// Catch block 3.
}
catch ([catch specification n])
{
// Catch block n.
}

It can have “n” number of catch blocks.

Catch: The catch specification for each block determines what exceptions will be caught and what variable is used to store the exception, if any. we can specify catch blocks for different types of exceptions.
The .NET Framework defines many different exception types for many of the common exceptions that can occur.
Few of exception types in namespace for example System.IO namespace that handle file I/O throw
the FileNotFoundException exception if an application attempts to access a nonexistent file. In addition, the common language runtime (CLR) itself throws a DivideByZeroException exception if you attempt to perform numeric division by zero. When an exception occurs, you do not have to include a catch block for every type of exception, and exceptions that are not matched will be propagated as described earlier.

If we are not specifying exception type in the catch block then it catches any type of exception

For example

//Try Block code
Try
{
}
//Catch Block Code
Catch
{
}

If we want to know what is the exception occurred we can access by using variable of exception declared in catch block

For example
catch (Exception ex)
{
// Catch block, can access exception in ex.
}

In above example “ex” will give the more information about exception

Important to Note:
 Exception types can implement a hierarchy of exceptions.
 For example,
 The .NET Framework provides an exception type called ArithmeticException, which you can   use to indicate an error when evaluating an arithmetic expression. The DivideByZeroException type is a specific classification of ArithmeticException (the .NET Framework also defines two other types of ArithmeticException called OverflowException and NotFiniteNumberException). If you catch the
DivideByZeroException exception, only that exception type is caught. However, if you catch the ArithmeticException exception, this catch block will trap DivideByZeroException, OverflowException, and NotFiniteNumberException. Therefore, if you have multiple catch blocks, you must ensure that you place the blocks.


Raising Exceptions

Creating an Exception object

1.     System.Exception
  System.SystemException
 System.FormatException
 System.ArgumentException
System.NotSupportedException

List describe the different types of Exception



Type
Description
FormatException
It throw this exception if the caller specified an argument that contains data that does not have the required format. For example, if the caller passes a string argument that does not contain information in the format that the method expects, the method should throw a FormatException exception.
ArgumentException
It throw this exception if the caller specifies an argument to a method that does not conform to the requirements of the method. You can use this exception type to indicate generalized errors with arguments, or you can use the ArgumentOutOfRangeException and
ArgumentNullException types to indicate more
specific errors (for example, if you pass the value 100 to a method, and the method expects a value between 1 and 99, or if you pass the value null as an argument).
NotImplementedException
It throw this exception to indicate that you have not yet implemented the code in a method.
This exception is primarily useful while you are
developing code when you have defined the
method, but have not written the code for the
body of the method
NotSupportedException
You can throw this exception if a caller attempts to perform an unsupported operation by using your method, such as specifying arguments that indicate that the caller wants to write to a read-only file.
FileNotFoundException
DirectoryNotFoundException
DriveNotFoundException
You can throw these exceptions in methods that
attempt to open files on behalf of a caller. If the
name of the file that is indicated by arguments that the caller specifies reference a file that does not exist, or the file is in a folder or drive that does not exist.





No comments:

Post a Comment