Sunday, 19 April 2015

Exception Handling C #

Basics : 
1. Exceptions are objects. They are used to handle code flow , where error might occur.
2. Exceptions are throw-n and catch -ed.
3. They are throm from try-block ,and catch-ed in catch block.

4. If an exception is thrown from line x , then rest of lines ( > x) in that try block are not executed.

try {
    Exception e = new Exception(" My first exception. ");
    throw e;
/* Followings will not be executed.*/
    TextReader reader = new StreamReader("FileName.txt");
    string line = reader.ReadLine();
    Console.WriteLine(line);
    reader.Close();
}
catch ( FileNotFoundException fnfe)
{
     Console.WriteLine(" This is printed when you try to open non-existing file");
}
catch ( Exception ex)
{
     Console.WriteLine( ex.message);
}

5. Base class Exceptions catches all derived class exceptions.
6. All classes derive directly or in-directly from class : Exception.

7. When flow enters a catch block , it will ignore other catch blocks. Thats why "FileNotFoundException" is put before "Exception" in above code. ( Point 6).

8. If u don't catch exception ,   it will be caught by CLR : Common Language Runtime.
9. Exception handler is code which catches Exception-s.

10. Funtions are pushed on stack when they are called , and poped out , when they finish.
    If a function generates an exception , then CLR starts looking for exception handler , starting from top of the stack.

What Exception Contains :

1. Message : 
2. Stack-trace : functions on stack at time when Exception is throw-n.
    Stack-trace contains :
at <namespace>.<class>.<method>  in  <Source file>.cs:line <line>
line number is displayed only when class is compiled with debug information. Thats why line number are not shown for .Net Assemblies.

3. If exception arises within constroctor , then stack-trace displays ".ctor" instead of constructor name.


Exception Hierarchy :

class ApplicationException :  Exception { ...  } // Exceptions thrown by applications developed by us.

class SystemException : Exception { ... } // Exceptions thrown by runtime.

No comments:

Post a Comment