0% found this document useful (0 votes)
41 views

Exception Handling

The document discusses exception handling in .NET. It defines basic terminology like exceptions, try/catch blocks, and finally blocks. It explains that exceptions are problems that occur during execution and exception handling allows programs to continue running or gracefully exit. Finally blocks are used to ensure cleanup code always runs regardless of exceptions. The .NET exception hierarchy with Exception as the base class is described. The key aspects of exception handling in .NET are covered at a high level.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Exception Handling

The document discusses exception handling in .NET. It defines basic terminology like exceptions, try/catch blocks, and finally blocks. It explains that exceptions are problems that occur during execution and exception handling allows programs to continue running or gracefully exit. Finally blocks are used to ensure cleanup code always runs regardless of exceptions. The .NET exception hierarchy with Exception as the base class is described. The key aspects of exception handling in .NET are covered at a high level.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 17

Exception Handling

Exception
Handling
Basic Terminology

• An exception is an indication of a problem that occurs during a program’s


execution.
• Exception handling enables programmers to create applications that can resolve
exceptions.
• In many cases, exception handling allows a program to continue executing as if no
problem was encountered. Programs that incorporate this feature are called fault-
tolerant.
• Programs typically request and release resources during execution. Such resources
usually include files on a disk. Often these resources are in use and can be used only
one at a time. A technique must be deployed that enables a program to use a
resource and then release the resource for use by other programs.
• The base class of all exception classes is found in the namespace System.Exception.
• Arithmetic overflow is a particular kind of exception.
Exception Handling Overview

• Typical program logic proceeds as follows:


Perform a task
If the preceding task did not execute correctly
Perform error processing
Perform next task
If the preceding task did not execute correctly
Perform error processing
• Exception handling enables the programmer to remove error-handling code from the
“main line” of the program’s execution. Programmers can decide to handle whatever
exceptions they choose.
• Exception handling is designed to process synchronous errors – errors that occur
during the normal program flow of control.
• Common exceptions:
– Out-of-range array subscripts,
– Division by zero,
– Invalid method parameters,
– Out of memory
Exception Handling Overview

• Exceptions not handled by User-defined Exception Handlers:


– Disk I/O completions,
– Network message arrivals,
– Mouse Clicks,
– Keystrokes
• Exception-handling is used for processing problems that occur when a program interacts with
software elements such as methods, constructors, assemblies, and classes. Rather than
handling problems that occur, such software elements use exceptions to notify programs when
problems occur.
• When a method detects an error and is unable to handle, it throws an exception.
• There is no guarantee that there will be an exception handler – code that executes when the
program detects an exception. If there is, the exception will be caught and handled.
• C# uses try blocks to enable exception handling. Following the try block are zero or more catch
blocks. Each catch handler specifies in parentheses an exception parameter that represents the
type of exception the catch handler can handle.
• A parameterless catch handler catches all exception types.
• After the last catch handler, an optional finally block contains code that always executes,
regardless whether the exception occurred or not.
Exception Handling Overview

• The point in a program at which an exception occurs is called a throw point.


• If an exception occurs in a try block, the try block expires (terminates
immediately) and program control transfers to the first catch handler following
the try block.
• The CLR searches for the first catch handler that can process the type of exception
that occurred. The CLR locates the matching catch by comparing the thrown
exception’s type to each catch’s exception-parameter type until the CLR finds a
match.
• A match occurs if the types are identical or if the thrown exception’s type is a derived
class of the exception-parameter type.
DivideByZero Exception

• Code Example

Study the different


catch blocks
.NET Exception Hierarchy

• The exception-handling mechanism allows objects of class Exception and


its derived classes to be thrown and caught. It’s possible to catch
exceptions of types that are not derived from class Exception using a
parameterless catch handler.
• Class Exception of namespace System is the base class of the .NET framework
exception hierarchy. Two important derived classes of Exception:
– ApplicationException,
– SystemException
• The CLR can generate SystemExceptions at any point during the execution of the
program. These are called runtime exceptions.
• Example: Attempt to access an out-of-range array subscript causes the CLR to throw
and IndexOutOfRangeException.
• Another common example occurs when the program uses an object reference to
manipulate an object that is null. The CLR throws a NullReferenceException.
• A catch handler can catch exceptions of a particular type or can use a base-class
type to catch exceptions in a hierarchy of related exception types.
.NET Exception Hierarchy

• A catch handler that specifies an exception parameter of type Exception


also can catch exceptions of all classes that extend Exception,
because Exception is the base class of all exception classes.
• This allows for polymorphic processing of related exceptions.
• For methods in the .NET Framework classes, we can look at 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 thrown by the method.
• Example: Convert.ToInt32 exceptions: {ArgumentException, FormatException,
OverflowException}
• To determine when the CLR throws exceptions, consult the C# Language
Specification: Help > Contents > Visual Studio .NET > Visual Basic and Visual C#
> Reference > Visual C# Language > C# Language Specification.
The “finally” Block

1. Programs request and release resources dynamically during execution.


2. Example: Program reading a file from a disk:
1. Request the opening of that file
2. If request succeeds, read the contents of the file
3. Only one process at a time can access the file
4. When finished processing the file, close the file. This prevents resource leaks.
3. A memory leak occurs when a program allocates memory (a with the new
operator) but does not deallocate memory when that memory is no longer neeed.
In C#, garbage collection prevents this.
4. A program that processes a file might receive an IOException during the
processing. Thus, file processing code should typically appear within a try block.
5. A finally block is guaranteed to execute if program control enters its
corresponding try block. The finally block will execute whether the try block
terminates or not. Resource deallocation usually occurs in the finally block.
6. If one or more catch hanlders follow a try block, the finally block is optional. If no
catch handlers follow a try block, a finally block must appear immediately after the
try block. If any catch handlers follow a try block, the finally block must appear
immediately after the last catch block.
The “finally” Block

Code Example
Exception Properties

• The Exception class has several properties.


– Message
– StackTrace
– InnerException
• The Message property stores the error message associated with the Exception object
• May be the default message or a customized message passed to the object’s
constructor.
• Stacktrace contains a string that represents the method call stack. The runtime
environment keeps a list of method calls that have been made up to a given moment.
• The StackTrace string represents a sequential list of methods that had not finished
processing at the time the exception occurred. The location at which the exception
occurs is called the throw point.
• This property wraps exception objects caught in code and then throws a new
exception based on their libraries.
Exception Properties

• Example:
– Accounting system might have account-number processing code in which account
numbers are input a strings, but represented with integers in the code.
- Convert.ToInt32 can throw a FormatException when it encounters an invalid number format.
- When an invalid account-number format occurs, the accounting system code might need to
indicate an error message different from the one supplied by FormatException or to indicate
a new exception such as InvalidAccountNumberFormatException.
- In this case, the program supplies code to catch the FormatException, then create an
exception object in the catch handler, passing original execution as one of the constructor
arguments.
- The original exception object becomes the InnerException of the new exception object.
- Code Example
Exception Properties
Programmer-Defined Exceptions

• In some cases programmers may wish to create exception types that


are more specific to the problems that occur in their programs.
• Programmer-defined exception classes should derive directly or indirectly
from class ApplicationException of namespace System
• Programmer-defined exception
• Exerciser for Programmer Exception
Operators “checked” and “unchecked”

• In .NET, primitive data types are stored in fixed-size structures.


• Max value for int is 2,147,483,647.
• A value larger than that would cause overflow.
• C# provides operators checked and unchecked to specify whether integer arithmetic
occurs in a checked or unchecked context.
• In a checked context, the CLR throws an OverflowException if one happens.
• In an unchecked context, the result is truncated if overflow occurs.
• Code Example
Assignment

You might also like