• Save
Exception handling
Upcoming SlideShare
Loading in...5
×
 

Exception handling

on

  • 3,826 views

 

Statistics

Views

Total Views
3,826
Views on SlideShare
3,825
Embed Views
1

Actions

Likes
1
Downloads
0
Comments
0

1 Embed 1

http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Exception handling Exception handling Presentation Transcript

    • Exception Handling
    • by N.Sanjeeva Reddy
  • 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  }
    • How to Handle Exceptions:
    • In .NET we have the try and catch block that enables us to handle the exceptions.
    • try
    • {
    • // Code where we are anticipating Exceptions
    • }
    • catch (Exception)
    • {
    • // Code to Handle the Exception
    • }
    • finally
    • // Code that needs to be executed in any case
    • // typically cleaning up code
    • }
    • try-catch-finally block in C#:
    •   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:
    • 1. Out Of Memory Exception
    • 2. Null Reference Exception
    • 3.  Invalid Cast Exception
    • 4.  Array Type Mismatch Exception
    • 5.  Index Out Of Range Exception
    • 6.  Arithmetic Exception
    • 7.  Divide By Zero Exception
    • 8.  Over Flow Exception
    • 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.
    •  
    • try
    • {
    • int i = 0;
    • String str = String.Empty;
    • Hashtable ObjHashTable = new Hashtable();
    • // Here the actual code
    • ----
    • }
    • catch (Exception)
    • // Code Handle the Exception
    • }
    • Exceptions are caught in the Catch Block. Once an Exception is caught, there are number of ways for handling the same.
    • Catching an Exception
    • 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.
    • try
    • {
    • // Code where we are anticipating the Exception
    • }
    • catch (Exception)
    • //Do Nothing
    • // Just Eat Away the Exception
    • }
  • 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("Error Message: This is the Message shown to the User"); } The message shown to the user can be an error message, warning message or an Information message.
  • 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.
  • 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.
    • Example of un-handled exception:
    • 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. 
    •    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.
        • //C#: Exception Un - Handled using System; class UnHandledException { public static void Main() { int x = 0; int intTemp = 100/x; Console.WriteLine(intTemp); } } 
  •   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); } } }   
  • 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); } }  
  •   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
  • 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; ); }
  • 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
  • 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); } } 
  • 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); } } 
  • 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;); } } 
    • Standard Exceptions 
    • Exception are categorised into two types 
    • exceptions generated by an executing program 
    • exceptions generated by the common language runtime. 
    • System.Exception is the base class for all exceptions in C#.
    • 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 generally not recommended to catch System Exceptions also it is not good programming practice to throw SystemExceptions in applications.
    • Following are few of the example of the above stated exception.
    • System.OutOfMemoryException 
    • System.NullReferenceException 
    • Syste.InvalidCastException 
    • Syste.ArrayTypeMismatchException 
    • System.IndexOutOfRangeException 
    • System.ArithmeticException 
    • System.DevideByZeroException 
    • System.OverFlowException 
  • 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;); }
  • catch(Exception e) { Console.WriteLine(&quot;Exception caught here&quot; + e.ToString()); } Console.WriteLine(&quot;Final Statement that is executed &quot;); } } 
    • Thank You !