English speaking and learning Interview Questions and Answers Programs C# Concept OOPS Concept JOBS

Monday, June 5, 2017

Exception Handling in C#

An exception is an error that occurs at runtime. By exception handling , you can, in a structured and controlled manner, handle runtime errors. exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running .Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. 

There are times when you don’t know if an error will occur. For example, you can’t predict when you’ll receive a file I/O error, run out of system memory, or encounter a database error. These things are generally unlikely, but they could still happen and you want to be able to deal with them when they do occur. This is where exception handling comes in. When exceptions occur, they are said to be “thrown”. What is actually thrown is an object that is derived from the System.Exception class.Exceptions are represented by classes. All exception classes must be derived from the built-in exception class Exception, which is part of the System namespace. Thus, all exceptions are subclasses of Exception. 
  • C# exception handling is managed via four keywords: try, catch, throw, and finally.
The general form of try-catch-finally in C# is shown below. 
// Statement which can cause an exception. 
catch(Type x) 
// Statements for handling the exception 
//Any cleanup code 

  • If any exception occurs inside the try block then 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 occurring inside the try block then the control directly transfers to the finally block. We can say that the statements inside the finally block is executed always.

Exceptions have the following properties:

  •  Exceptions are types that all ultimately derive from System.Exception. 
  • Use a try block around the statements that might throw exceptions. 
  • Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. 
  • In C#, the catch keyword is used to define an exception handler.
  •  If no exception handler for a given exception is present, the program stops executing with an error message. 
  • Do not catch an exception unless you can handle it and leave the application in a known state. 
  • If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred. 
  • Exceptions can be explicitly generated by a program by using the throw keyword. 
  • Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error. 
  • Code in a finally block is executed even if an exception is thrown. Use a finally block to release resources, for example to close any streams or files that were opened in the try block. 
Useful Properties of Exception
  1. Message -  Gets a message that describes the current exception.
  2. StackTrace The execution stack keeps track of all the methods that are in execution at a given instant. A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs.
  3. InnerException - An object that describes the error that caused the current exception. The InnerException property returns the same value as was passed into the Exception(String, Exception) constructor, or null if the inner exception value was not supplied to the constructor. This property is read-only.
Useful Methods 
  1. Finalize - The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.
  2. GetType -Gets the runtime type of the current instance.
  3. ToString() - Creates and returns a string representation of the current exception.
Example- How to use InnerException to retain current exception

Step 1- We are making a program of Division.in this user have to provide numerator and denominator.If any exception occurs, we are writing this exception to C:\Log\Log.txt file.

Step 2-  Exception can occurs from many scenario. suppose- user has enter denominator=0 , we should get "Attempted to divide by zero".
When exception is coming.we are writing it to log file.if log file does not exist or someone has changed it name to Log1.txt, we will get exception of  "filenotfound" .

Step 3 - original reason for exception is "Attempted to divide by zero" . So to retain the original exception pass it as a parameter to the constructor, of the current exception and show it by ex.InnerException.Message.

Code - 

using System;
using System.IO;
class ExceptionHandling
    public static void Main()
                Console.WriteLine("Enter First Number");
                int FirstNumber = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter Second Number");
                int SecondNumber = Convert.ToInt32(Console.ReadLine());

                int Result = FirstNumber / SecondNumber;
                Console.WriteLine("Result = {0}", Result);
            catch (Exception ex)
                string filePath = @"C:\Log\Log.txt";
                if (File.Exists(filePath))
                    StreamWriter sw = new StreamWriter(filePath);
                    Console.WriteLine("Please check after some time");
                    //To store the original exception pass it as a parameter
                    //to the constructor, of the current exception
                    throw new FileNotFoundException(filePath + " Does not Exist", ex);
        catch (Exception ex)
            //ex.Message will give the current exception message
            Console.WriteLine("Current or Outer Exception = " + ex.Message);

            //check if innerexception is not null 
            if (ex.InnerException != null)
                Console.WriteLine("Inner Exception = {0}", ex.InnerException.Message);


No comments :

Post a Comment