Exception Handling

  • In this article we will learn:

    • What exceptions are and how they are handled?
    • When to use exception handling?
    • To use try blocks to delimit code in which exceptions might occur
    • To throw exceptions to indicate a problem
    • To use catch blocks to specify exception handlers
    • To use the finally block to release resources
    • The .NET exception class hierarchy
    • Exception properties
    • To create user-defined exceptions
  • Exception:

    • is an indication of a problem that occurs during a program’s execution
  • Advantages of using Exception Handling:

    • Exception handling enables programmers to remove error-handling code from the "main line" of the program’s execution, improving program clarity and enhancing modifiability
    • In many cases, handling an exception allows a program to continue executing as if no problems were encountered
    • Exception handling helps improve a program’s fault tolerance (مقاومة الأعطال)
  • Notes:

    • intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug especially in large applications
    • With programming languages that do not support exception handling, programmers often delay writing error-processing code and sometimes forget to include it. This results in less robust software products
  • Example (1):

    • Dividing by zero
    • Division by zero with floating-point values is allowed. Such a calculation results in the value infinity, which is represented by either constant Double.PositiveInfinity or constant Double.NegativeInfinity, depending on whether the numerator is positive or negative. These values are displayed as Infinity or -Infinity. If both the numerator and denominator are zero, the result of the calculation is the constant Double.NaN ("not a number"), which is returned when a calculation’s result is undefined
  • Uncaught Exceptions:

    • is an exception for which there is no matching catch block
  • If you run the application from Visual Studio with debugging and the runtime environment detects an uncaught exception, the application pauses, and a window called the Exception Assistant appears indicating where the exception occurred, the type of the exception and links to helpful information on handling the exception
  • Termination model of exception handling:

    • After the exception is handled, program control does not return to the throw point because the try block has expired (which also causes any of its local variables to go out of scope)
  • Resumption model of exception handling:

    • in which after an exception is handled, control resumes just after the throw point
  • The Try block and its corresponding catch and finally blocks together form a try statement. It is important not to confuse the terms "try block" and "try statement "the term "Try block" refers to the block of code following the keyword try (but before any catch or finally blocks), while the term "Try statement" includes all the code from the opening Try keyword to the end of the last catch or finally block. This includes the Try block, as well as any associated catch blocks and finally block
  • .Net Exception Hierarchy:

    • Class Exception of namespace System is the base class of the .NET Framework exception class hierarchy. Two of the most important classes derived from Exception are ApplicationException and SystemException. ApplicationException is a base class that programmers can extend to create exception classes that are specific to their applications
    • The CLR generates SystemExceptions, which can occur at any point during program execution. Many of these exceptions can be avoided if applications are coded properly. For example, if a program attempts to access an out-of-range array index, the CLR throws an exception of type IndexOutOfRangeException (a derived class of SystemException). Similarly, an exception occurs when a program uses an object reference to manipulate an object that does not yet exist (i.e., the reference has a value of null). Attempting to use a null reference causes a NullReferenceException (another derived class of SystemException).
    • Other SystemException types thrown by the CLR include OutOfMemoryException, StackOverflowException and ExecutionEngineException. These are thrown when the something goes wrong that causes the CLR to become unstable. In some cases, such exceptions cannot even be caught. In general, it is best to simply log such exceptions then terminate your application
  • It is a compilation error if a catch block that catches a base-class exception is placed before a catch block for any of that class’s derived-class types. If this were allowed, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute
  • How do we determine that an exception might occur in a program? For methods contained in the .NET Framework classes, read the detailed descriptions of the methods in the online documentation. If a method throws an exception its description contains a section called Exceptions that specifies the types of exceptions the method throws and briefly describes possible causes for the exceptions
  • Resource leak:

    • if you don’t closed a file after using
  • In programming languages such as C and C++, in which the programmer (not the language) is responsible for dynamic memory management, the most common type of resource leak is a memory leak. A memory leak occurs when a program allocates memory (as C# programmers do via keyword new), but does not deallocate the memory when it is no longer needed. Normally, this is not an issue in C#, because the CLR performs garbage collection of memory that is no longer needed by an executing program
  • The CLR does not completely eliminate memory leaks. The CLR will not garbage collect an object until the program contains no more references to that object. Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects
  • Typically, exceptions occur when processing resources that require explicit release. For example, a program that processes a file might receive IOExceptions during the processing. For this reason, file processing code normally appears in a TRy block. Regardless of whether a program experiences exceptions while processing a file, the program should close the file when it is no longer needed
  • The finally block, is guaranteed to execute regardless of whether the try block executes successfully or an exception occurs. This makes the finally block an ideal location in which to place resource-release code for resources that are acquired and manipulated in the corresponding try block
  • A finally block typically contains code to release resources acquired in the corresponding Try block, which makes the finally block an effective mechanism for eliminating resource leaks.
  • If one or more catch blocks follow a try block, the finally block is optional. However, if no catch blocks follow a try block, a finally block must appear immediately after the try block. If any catch blocks follow a try block, the finally block (if there is one) appears after the last catch block. Only whitespace and comments can separate the blocks in a try statement.
  • Throwing an exception from a finally block can be dangerous. If an uncaught exception is awaiting processing when the finally block executes, and the finally block throws a new exception that is not caught in the finally block, the first exception is lost, and the new exception is passed to the next enclosing try block
  • Do not place try blocks around every statement that might throw an exception, because this can make programs difficult to read. It is better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each of the possible exceptions. Then follow the catch blocks with a single finally block. Separate try blocks should be used when it is important to distinguish between multiple statements that can throw the same exception type
  • using statement (not to be confused with the using directive for using namespaces)simplifies writing code in which you obtain a resource, use the resource in a try block and release the resource in a corresponding finally block
  • The most two important properties in class Exception are Message and StackTrace
  • StackTrace:

    • Contains a string that represents the method-call stack. Recall that the runtime environment at all times keeps a list of open method calls that have been made but have not yet returned. The StackTrace represents the series of methods that have not finished processing at the time the exception occurs
  • InnerException:

    • Let you know the exceptions that are made by the object you have caught
  • Class Exception provides other properties, including HelpLink, Source and TargetSite. Property HelpLink specifies the location of the help file that describes the problem that occurred. This property is null if no such file exists. Property Source specifies the name of the application where the exception occurred. Property TargetSite specifies the method where the exception originated
  • Unwinds Concept
  • When catching and rethrowing an exception, provide additional debugging information in the rethrown exception. To do so, create an Exception object containing more specific debugging information, then pass the original caught exception to the new exception object’s constructor to initialize the InnerException property
  • If I’m handling exceptions professionally display all the exception information you can compose them and throw them in one exception
  • Associating each type of malfunction with an appropriately named exception class improves program clarity
  • Associating each type of malfunction with an appropriately named exception class improves program clarity
  • Before creating a user-defined exception class, investigate the existing exceptions in the .NET Framework Class Library to determine whether an appropriate exception type already exists

According to "Best Practices for Handling Exceptions [C#]," user-defined exceptions should extend class ApplicationException, have a class name that ends with "Exception" and define three constructors: a parameterless constructor; a constructor that receives a string argument (the error message); and a constructor that receives a string argument and an Exception argument (the error message and the inner exception object). Defining these three constructors makes your exception class more flexible, allowing other programmers to easily use and extend it

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s