Exception Handling in .NET Framework

Содержание

Слайд 2

Contents Introduction to structured exception handling Construct «try..catch» «Exception» class and

Contents

Introduction to structured exception handling
Construct «try..catch»
«Exception» class and exception hierarchy in.NET

Framework
Exception throwing and re-rising
Creating own exceptions
Construct «try..finally»
Best practices for exception handling
References to additional sources
Слайд 3

1. Introduction to structured exception handling

1. Introduction to structured exception handling

Слайд 4

There are possible situations during the application execution when predetermined plan

There are possible situations during the application execution when predetermined plan

of actions may be changed
Developer should provide ways to ensure correct execution despite possible errors

Main task – correct operation of the application

There are different kinds of errors reactions on which may be different and some may be corrected and some – don't:
Software errors created by developer like reading of non-initialized variable;
System errors and failures with resources, like memory exhaustion and file read errors;
User errors like incorrect data input.

Слайд 5

Obsolete error handling method is based on multiple checks of input

Obsolete error handling method is based on multiple checks of input

data and operation return codes.
Drawbacks:
difficulties;
bloated code;
unreliable.

Obsolete check-based method

int IOResult = ReadFileWithIOResult("somefile.txt");
if (IOResult != 0)
{
// Exception here, action required
}
else
{
// File read successfully continuing normal execution
}

Слайд 6

Modern way to handle errors provides using of special mechanism –

Modern way to handle errors provides using of special mechanism –

structured exception handling which is the part of programming language
Exception is an event which happens during software execution and changes normal way of code execution
Exceptions in .NET Framework are instances of classes inherited from base class Exception. Only instances of this class and inherited classes may participated in structured exception handling.

Structured exception handling

Слайд 7

2. Construct «try..catch»

2. Construct «try..catch»

Слайд 8

try { // Code which may result in exception } catch

try
{
// Code which may result in exception
}

catch
{
// Code executed only in case of exception
}

Simplest "try..catch" constuct

Слайд 9

try { // Code which may result in exception } catch

try
{
// Code which may result in exception
}

catch (DivideByZeroException)
{
// Code executed in case of exception
}

"try..catch" construct with specific exception

Слайд 10

try { // Code which may result in exception catch (DivideByZeroException)

try
{
// Code which may result in exception
catch

(DivideByZeroException)
{
// Code executed in case of exception type DivideByZeroException
}
catch (Exception)
{
// Code executed in case of exception type Exception
// Means "any exception"
}

Cascade sections of catch

Слайд 11

"try..catch" construct with instance of exception try { // Code which

"try..catch" construct with instance of exception


try
{
// Code

which may result in exception
}
catch (Exception e)
{
// Code executed in case of exception
// Using object e to get access to properties of exception
Console.WriteLine(e.Message);
// Re-rising same exception
throw;
}
Слайд 12

3. «Exception» class and exception hierarchy in.NET Framework

3. «Exception» class and exception hierarchy in.NET Framework

Слайд 13

Exception is a base class for all exceptions исключений Important properties:

Exception is a base class for all exceptions исключений
Important properties:
Message –

user-oriented message about error
Source – name of an error source (application or object)
InnerException – inner exception (if called from other)
StackTrace – call stack to the point of exception call
TargetSite – method name which raised an exception
HelpLink – URL-address to information about exception
Data – dictionary with additional information with exception (IDictionary)

Exception class

Слайд 14

Exception hierarchy in .NET Framework

Exception hierarchy in .NET Framework

Слайд 15

4. Exception throwing and re-rising

4. Exception throwing and re-rising

Слайд 16

Exception throwing public static void Demo(string SomeRequiredArg) { // Check if

Exception throwing

public static void Demo(string SomeRequiredArg)
{
// Check if

some required argument is null
if (SomeRequiredArg == null)
{
// Exception throwing
throw new ArgumentNullException("Argument SomeRequiredArg is null");
}
}
Слайд 17

Exception re-rising try { // Code which may rise an exception

Exception re-rising


try
{
// Code which may rise an

exception
}
catch (Exception e)
{
// Exception handling code
// Using object e to get access to exception properties
Console.WriteLine(e.Message);
// Rising same exception again
throw;
}
Слайд 18

5. Creating own exceptions

5. Creating own exceptions

Слайд 19

Exception declaration class SampleException: ApplicationException { }; It is recommended to

Exception declaration
class SampleException: ApplicationException { };

It is recommended to create

own exceptions based on class ApplicationException.
Simplest declaration:
class SpecificSampleException: SampleException { };

To declare specific exceptions developers should create hierarchies of exceptions:

Слайд 20

MSDN recommendations for exception declarations Minimal possible declaration for exception declaration

MSDN recommendations for exception declarations

Minimal possible declaration for exception declaration described

in MSDN requires use of Serializable attribute and definition of four constructors:
default constructor;
constructor which sets Message property;
constructor which sets Message and InnerException properties;
constructor for serialization.
[Serializable()]
public class InvalidDepartmentException : ApplicationException
{
public InvalidDepartmentException() : base() { }
public InvalidDepartmentException(string message) : base(message) { }
public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }
// A constructor is needed for serialization when an
// exception propagates from a remoting server to the client.
protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) { }
}
Слайд 21

6. Construct «try..finally»

6. Construct «try..finally»

Слайд 22

«try..finally» used when it is required to guarantee execution of some

«try..finally» used when it is required to guarantee execution of some

code
May be used together with catch

Using finally

try
{
// Code which may raise an exception
}
finally
{
// Code which should be executed on any condition
}

Слайд 23

7. Best practices for exception handling

7. Best practices for exception handling

Слайд 24

Do not catch general exceptions (do not use catch without parameters

Do not catch general exceptions (do not use catch without parameters

or catch(Exception) )
Create own exceptions based on ApplicationException class but not on SystemException
Do not use exceptions for application execution control flow as exception handling is heavy resource usage task. Exceptions should be used to manage errors only
Do not mute exceptions which can’t be handled in application context (system errors and failures).
Do not raise general exceptions: Exception, SystemException, ApplicationException
Do not generate reserved system exceptions: ExecutionEngineException, IndexOutOfRangeException, NullReferenceException, OutOfMemoryException
Do not return an exception instance as a method return result instead of using throw.
Do not create exceptions used only for debugging purposes. Do define debug-only exceptions use Assert.

Best practices for exception handling

Слайд 25

MSDN recommendations for creating exceptions: http://msdn.microsoft.com/en-us/library/ms173163.aspx MSDN recommendation for exception generation:

MSDN recommendations for creating exceptions: http://msdn.microsoft.com/en-us/library/ms173163.aspx
MSDN recommendation for exception generation: http://msdn.microsoft.com/en-us/library/ms182338.aspx
Full hierarchy of

Microsoft .NET Framework exceptions (code sample in comments): http://stackoverflow.com/questions/2085460/c-sharp-is-there-an-exception-overview

8. References to additional sources