CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    .NET Framework General: What are exceptions?

    Q: What are exceptions?

    A: Exceptions represent a breach of an implicit assumption made within code. For example, if your code tries to access a file that is assumed to exist, but the file is missing, an exception would be thrown. However, if your code does not assume that the file exists and checks for its presence first, this scenario would not necessarily generate an exception.

    Exceptions are not necessarily errors. Whether or not an exception represents an error is determined by the application in which the exception occurred. An exception that is thrown when a file is not found may be considered an error in one scenario, but may not represent an error in another.


    • Can I have some advice on handling exceptions?


      • Know when to set up a 'try/catch' block. For example, you can programmatically check for a condition that is likely to occur without using exception handling. In other situations, using exception handling to catch an error condition is appropriate.

      • Use 'try/finally' blocks around code that can potentially generate an exception and centralize your catch statements in one location. In this way, the 'try' statement generates the exception, the 'finally' statement closes or deallocates resources, and the 'catch' statement handles the exception from a central location.

      • Always order exceptions in 'catch' blocks from the most specific to the least specific. This technique handles the specific exception before it is passed to a more general 'catch' block.

      • End exception class names with the word "Exception". For example:


        Code:
         
        [COLOR=#008800]// Visual Basic
        Public Class EmployeeListNotFoundException Inherits Exception
        
        
        // C#
        public class MyFileNotFoundException : ApplicationException {}
      • In most cases, use the predefined exceptions types. Define new exception types only for programmatic scenarios. Introduce a new exception class to enable a programmer to take a different action in code based on the exception class.

      • Do not derive user-defined exceptions from the 'Exception' base class. For most applications, derive custom exceptions from the 'ApplicationException' class.

      • Include a localized description string in every exception. When the user sees an error message, it is derived from the description string of the exception that was thrown, rather than from the exception class.

      • Use grammatically correct error messages, including ending punctuation. Each sentence in a description string of an exception should end in a period.

      • Provide exception properties for programmatic access. Include extra information in an exception (in addition to the description string) only when there is a programmatic scenario where the additional information is useful.




    • How do I handle exceptions?

      You can use the 'Try/Catch/Finally' statements for structured exception handling. This allows you to execute a particular block of statements if a specified exception occurs while your code is running. When this happens, the code is said to 'throw' the exception, and you 'catch' it with the appropriate 'Catch' statement.

      Execution enters the 'Try/Catch/Finally block with the statement block following the 'Try' statement. If Visual Basic/C# completes this block without an exception being generated, it looks for the optional 'Finally' statement at the end. If you have supplied the 'Finally' statement, Visual Basic executes the statement block following it. In any case, control is then transferred to the statement following the 'End Try' statement.

      If an exception occurs, Visual Basic/C# examines the 'Catch' statements in the order they appear within 'Try/Catch/Finally'. If it finds a 'Catch' statement that handles the generated exception, it executes the corresponding statement block. When it has finished executing the 'Catch' block, it executes the 'Finally block if it is present. Execution then proceeds to the statement following the 'End Try' statement.

      A 'Catch' statement handles an exception that is of the same type as the type declared in the 'Catch' statement, or of a type derived from it. If you supply a 'Catch' statement that does not specify an exception type, it handles any exception derived from the 'Exception' class. If such a statement is the last 'Catch' statement, it can catch any exception that you did not handle in the preceding 'Catch' blocks



    • Can I have an example on handling exceptions?

      In the following Visual Basic example, 'Try/Catch/Finally' attempts to calculate the date and time exactly 100 years from the value provided in the 'Object' variable 'GivenDate':


      Code:
      Dim GivenDate As Object ' Should contain date/time information.
       
      Dim NextCentury As Date
       
      Try
       
      NextCentury = DateAdd("yyyy", 100, GivenDate)
       
      Catch ThisExcep As System.ArgumentException
       
      ' At least one argument has an invalid value.
       
      Catch ThisExcep As ArgumentOutOfRangeException
       
      ' The result is later than December 31, 9999.
       
      Catch ThisExcep As InvalidCastException
       
      ' GivenDate cannot be interpreted As a date/time.
       
      Catch
       
      ' An unforeseen exception has occurred.
       
      Finally
       
      ' This block is always executed before leaving.
       
      End Try
      The exceptions that you can anticipate from the 'DateAdd()' function can be handled in the first three 'Catch' blocks, and you can deal with any unexpected exception in the last 'Catch' block. No matter what happens, the 'Finally' block is always the last code to be executed before leaving 'Try/Catch/Finally'.

      If 'ThisExcep' does not appear in a declaration statement such as 'Dim', the 'Catch' statement with the 'As' clause serves as a declaration of the exception variable.


      In the following C# example...
      Code:
      using System;
       
      class Test
      {
        static void F()
        {
          try
          {
            G();
          }
          catch (Exception e)
          {
            Console.WriteLine("Exception in F: " + e.Message);
            e = new Exception("F");
            throw; // re-throw
          }
        }
       
        static void G()
        {
          throw new Exception("G");
        }
      
        static void Main()
        {
          try
          {
            F();
          }
          catch (Exception e)
          {
            Console.WriteLine("Exception in Main: " + e.Message);
          }
        }
      }
      ...the method 'F()' catches an exception, writes some diagnostic information to the console, alters the exception variable, and re-throws the exception. The exception that is re-thrown is the original exception, so the output produced is:


      Code:
      Exception in F: G
      
      Exception in Main: G
      If the first catch block had thrown 'e' instead of rethrowing the current exception, the output produced is would be as follows:


      Code:
       
      Exception in F: G
       
      Exception in Main: F
      It is a compile-time error for a 'break', 'continue' or 'goto' statement to transfer control out of a 'finally' block. When a 'break', 'continue' or 'goto' statement occurs in a 'finally' block, the target of the statement must be within the same 'finally' block, or otherwise a compile-time error occurs.



    Last edited by Andreas Masur; April 14th, 2006 at 06:55 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured