Exception handling


Published on

Published in: Education

Exception handling

  1. 1. <ul><li>Exception Handling </li></ul><ul><li>by N.Sanjeeva Reddy </li></ul>
  2. 2. What is exception? Exceptions are unusual error conditions that occur during execution of a program or an application. In C# exception handling is achieved using the try ? catch ? finally block. All the three are C# keywords that are used do exception handling. The try block encloses the statements that might throw an exception where as catch block handles any exception if one exists. The finally block can be used for doing any clean up process. try { // Statements that are can cause exception } catch(Type x) { // Statements to handle exception } finally { // Statement to clean up  }
  3. 3. <ul><li>How to Handle Exceptions: </li></ul><ul><li>In .NET we have the try and catch block that enables us to handle the exceptions. </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Code where we are anticipating Exceptions </li></ul><ul><li>} </li></ul><ul><li>catch (Exception) </li></ul><ul><li>{ </li></ul><ul><li>// Code to Handle the Exception </li></ul><ul><li>} </li></ul><ul><li>finally </li></ul><ul><li>{  </li></ul><ul><li>// Code that needs to be executed in any case </li></ul><ul><li>// typically cleaning up code </li></ul><ul><li>} </li></ul>
  4. 4. <ul><li>try-catch-finally block in C#: </li></ul><ul><li>  As mentioned earlier any exception that occurs inside the try block, transfers control to the appropriate catch block and later to the finally block. 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.     Types of Exceptions: </li></ul><ul><li>1. Out Of Memory Exception </li></ul><ul><li>2. Null Reference Exception </li></ul><ul><li>3.  Invalid Cast Exception </li></ul><ul><li>4.  Array Type Mismatch Exception </li></ul><ul><li>5.  Index Out Of Range Exception </li></ul><ul><li>6.  Arithmetic Exception </li></ul><ul><li>7.  Divide By Zero Exception </li></ul><ul><li>8.  Over Flow Exception </li></ul>
  5. 5. <ul><li>The try and catch block are mandatory for handling exceptions. Finally, the block is optional. It is always a better practice to handle exceptions that are anticipated. If we are dealing with a database we need to handle the SQL Exception. The code on try should be the code that anticipates any kind of exception. It is a common practice that is observed that all the code in a function is moved to a try. Such programming should not be encouraged. </li></ul><ul><li>  </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>int i = 0; </li></ul><ul><li>String str = String.Empty; </li></ul><ul><li>Hashtable ObjHashTable = new Hashtable(); </li></ul><ul><li>// Here the actual code </li></ul><ul><li>---- </li></ul><ul><li>} </li></ul><ul><li>catch (Exception) </li></ul><ul><li>{  </li></ul><ul><li>// Code Handle the Exception </li></ul><ul><li>} </li></ul>
  6. 6. <ul><li>Exceptions are caught in the Catch Block. Once an Exception is caught, there are number of ways for handling the same. </li></ul><ul><li>Catching an Exception </li></ul><ul><li>This kind of handling mechanism is the least encouraged one. The problem with the approach given below is that if an exception is caught, it is not logged. This can have serious problems to the application while diagnosing in case of any problem. </li></ul><ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>// Code where we are anticipating the Exception </li></ul><ul><li>} </li></ul><ul><li>catch (Exception) </li></ul><ul><li>{  </li></ul><ul><li>//Do Nothing </li></ul><ul><li>// Just Eat Away the Exception </li></ul><ul><li>} </li></ul>
  7. 7. Showing an Error Message to User This kind of Exception Handling mechanism is the most commonly used mechanism. try { // Code where we are anticipating the Exception } catch (Exception) { System.Windows.Forms.MessageBox.Show(&quot;Error Message: This is the Message shown to the User&quot;); } The message shown to the user can be an error message, warning message or an Information message.
  8. 8. What are Custom Exceptions? Why do we need them? Custom Exceptions are exceptions that are created for applying the Business rules of the Application. These exceptions are used to implement the business rules violations of the application. For example: The minimum balance set for Savings A/C in a bank would be different from a Current A/C. Hence, while developing the application for the same the Business rule would be kept as the same. Violation of Business Rule: Whenever a Violation of Business rule is done, it should be notified and the proper message should be shown to the user. This will be handled by a Custom Exception. Let us illustrate the same with an example.
  9. 9. private void ValidateBeforeDebit(float Amount) { { if((Balance – Amount ) < MimimumBalanceNeedToHave) { throw new MimimumBalanceViolationForSavingsAccount(&quot;Current TransactionFailed: Minimum Balance not available&quot;); } Else { Debit(Amount); } } } We have a method ValidateBeforeDebit (). This method ensures the minimum balance. If there is no minimum balance then a Custom Exception of the type MimimumBalanceViolationForSavingsAccount is thrown. We need to handle the method whenever we call the method.
  10. 10. <ul><li>Example of un-handled exception: </li></ul><ul><li>The following program will encounter an exception when executed. At the time of compilation there will be no error caused. In the following code division by zero exception occurs. The division by zero is a runtime anomaly and program terminates with an error message.  </li></ul><ul><li>   Any un-handled exceptions finds the appropriate block where it is handled, if they are no appropriate blocks then the default .NET runtime will terminate the execution of the entire program. </li></ul><ul><ul><ul><li>//C#: Exception Un - Handled using System; class UnHandledException { public static void Main() { int x = 0; int intTemp = 100/x; Console.WriteLine(intTemp); } }  </li></ul></ul></ul>
  11. 11.   Example of handled exception: The above program can be modified in the following manner to track the exception. You can see the usage of standard DivideByZeroException class using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(?Program terminated before this statement?); } catch(DivideByZeroException de) { Console.WriteLine(&quot;Division by Zero occurs&quot;);  } finally  { Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } }   
  12. 12. In the above example the program ends in an expected way instead of program termination. At the time of exception program control passes from exception point inside the try block and enters catch blocks. As the finally block is present, so the statements inside final block are executed. Example of exception un handled in catch block As in C#, the catch block is optional. The following program is perfectly legal in C#.  using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } finally { Console.WriteLine(&quot;Inside Finally Block&quot;); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } }  
  13. 13.   The above example will produce no exception at the compilation time but the program will terminate due to un handled exception. But the thing that is of great interest to all the is that before the termination of the program the final block is executed.  Example of Multiple Catch Blocks:   A try block can throw multiple exceptions, that can handle by using multiple catch blocks. Important point here is that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.  //C#: Exception Handling: Multiple catch
  14. 14. using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch(DivideByZeroException de) { Console.WriteLine(&quot;DivideByZeroException&quot; ); } catch(Exception ee) { Console.WriteLine(&quot;Exception&quot; ); }
  15. 15. finally { Console.WriteLine(&quot;Finally Block&quot;); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } }  Example of 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
  16. 16. using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch { Console.WriteLine(&quot;oException&quot; ); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } 
  17. 17. The following program handles all exception with Exception object.  //C#: Exception Handling: Handling all exceptions using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch(Exception e) { Console.WriteLine(&quot;oException&quot; ); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } 
  18. 18. Example of Throwing an Exception: C# provides facility to throw an exception programmatically. The 'throw' keyword is used for doing the same. The general form of throwing an exception is as follows.  For example the following statement throw an ArgumentException explicitly.  throw new ArgumentException(&quot;Exception&quot;);  using System; class HandledException { public static void Main() { try { throw new DivideByZeroException(&quot;Invalid Division&quot;); } catch(DivideByZeroException e) { Console.WriteLine(&quot;Exception&quot; ); } Console.WriteLine(&quot;Final Statement that is executed&quot;); } } 
  19. 19. <ul><li>Standard Exceptions  </li></ul><ul><li>Exception are categorised into two types  </li></ul><ul><li>exceptions generated by an executing program  </li></ul><ul><li>exceptions generated by the common language runtime.  </li></ul><ul><li>System.Exception is the base class for all exceptions in C#. </li></ul><ul><li>The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. </li></ul><ul><li>The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is generally not recommended to catch System Exceptions also it is not good programming practice to throw SystemExceptions in applications. </li></ul><ul><li>Following are few of the example of the above stated exception. </li></ul><ul><li>System.OutOfMemoryException  </li></ul><ul><li>System.NullReferenceException  </li></ul><ul><li>Syste.InvalidCastException  </li></ul><ul><li>Syste.ArrayTypeMismatchException  </li></ul><ul><li>System.IndexOutOfRangeException  </li></ul><ul><li>System.ArithmeticException  </li></ul><ul><li>System.DevideByZeroException  </li></ul><ul><li>System.OverFlowException  </li></ul>
  20. 20. User-defined Exceptions: C#, allows to create user defined exception class this class should be derived from Exception base class. 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 UserDefinedException : Exception { public MyException(string str) { Console.WriteLine(&quot;User defined exception&quot;); } } class HandledException { public static void Main() { try { throw new UserDefinedException (&quot;New User Defined Exception&quot;); }
  21. 21. catch(Exception e) { Console.WriteLine(&quot;Exception caught here&quot; + e.ToString()); } Console.WriteLine(&quot;Final Statement that is executed &quot;); } } 
  22. 22. <ul><li>Thank You ! </li></ul>