introduction to exception handling and defensive programming

33
Introduction to Exception Handling and Defensive Programming

Upload: ashley-burke

Post on 03-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Exception Handling and Defensive Programming

Introduction to Exception Handling

and Defensive Programming

Page 2: Introduction to Exception Handling and Defensive Programming

Slide 2

Defensive Programming (Introduction) Code Complete puts it nicely

It’s defensive driving. You are never sure what others will do

We defend against others by Checking for invalid inputs

Page 3: Introduction to Exception Handling and Defensive Programming

Slide 3

Invalid Inputs All data from external sources should be

checked In the routines (procedures) you create,

check the input parameters too Apply an error-handling strategy when

errors are detected

Page 4: Introduction to Exception Handling and Defensive Programming

Slide 4

Error Handling Strategy There is no one-size-fits-all solution

Routines can return error codes We might shut down the program entirely Log and / or display messages

Closest legal value Next valid data item

Page 5: Introduction to Exception Handling and Defensive Programming

Slide 5

Exceptions Most languages work the similarly here

Java, VB, C# It’s a way a procedure can say

“Something is wrong and I don’t know what to do about it. I hope that you (caller) do.”

Page 6: Introduction to Exception Handling and Defensive Programming

Slide 6

Exceptions (Best Practices) Exceptions force other parts of a

program to deal with the exception Don’t unnecessarily throw exceptions

Anticipate errors, where possible, instead Don’t throw exceptions in constructors

and destructors Use the correct level of abstraction

Page 7: Introduction to Exception Handling and Defensive Programming

Slide 7

Exception Handling (Introduction) Exception - a run-time error that

occurs as a result of some abnormal condition

In Visual Studio, a dialog box appears in cases of an unhandled exception

Page 8: Introduction to Exception Handling and Defensive Programming

Slide 8

Exception Handling (Key Concepts) Catching an expression or handling

an exception - when an exception occurs, statements execute to process the exception in some way

Throwing an exception - a component may generate an exception that will be caught by another component

Page 9: Introduction to Exception Handling and Defensive Programming

Slide 9

The Exception Object (Introduction) Remember that everything in .NET is an

object Exceptions are no “exception”

The .NET Framework defines a class named Exception and numerous derived classes

Page 10: Introduction to Exception Handling and Defensive Programming

Slide 10

The Exception Object (Members) The ToString method converts the

error message to a string The Message property stores the same

message The StackTrace property shows where

the exception occurred and the call stack This is the same call stack that we

discussed during the debugging lecture

Page 11: Introduction to Exception Handling and Defensive Programming

Slide 11

Exception Handling C# C# uses the try, catch, and finally,

blocks to build structured exception handlers

Structured exception handlers are just a specialized form of a decision-making statement They are really just a form of switch

statement

Page 12: Introduction to Exception Handling and Defensive Programming

Slide 12

Exception Handling Syntax (1) The try, catch, and finally, blocks

declare a structured exception handler Syntax

try Statements that could cause an exception

catch exception name Code that executes when an exception occurs in the Try block

Page 13: Introduction to Exception Handling and Defensive Programming

Slide 13

Exception Handling Syntax (2) Syntax (cont)

[ catch exception name ] Code that executes when an exception occurs in the Try block

[ finally ] Statements that always execute

regardless of whether an exception occurs

Statements following exception handler

Page 14: Introduction to Exception Handling and Defensive Programming

Slide 14

Exception Handling Details (1) The statements in the try block contain

statements that could cause an exception to be thrown

If an exception is thrown, the statements in a catch block execute An exception handler may have multiple catch blocks to handle different types of exceptions

Page 15: Introduction to Exception Handling and Defensive Programming

Slide 15

Exception Handling Details (2) Statements in the optional finally block

always execute, regardless of whether an exception occurred.

The optional finally block typically contains statements to perform housekeeping chores such as closing files or closing database connections

name argument defines a variable to store the exception

This variable works like a block-scoped variable This is a reference type

As exception clause contains the name of the exception that the catch block should handle

Page 16: Introduction to Exception Handling and Defensive Programming

Slide 16

Control Flow of Exceptions

Page 17: Introduction to Exception Handling and Defensive Programming

Slide 17

Propagating Exceptions It’s possible that the currently executing

procedure has no exception handler The call stack is searched for an

“active” exception handler

Page 18: Introduction to Exception Handling and Defensive Programming

Slide 18

Propagating Exceptions Illustration (VB)

Page 19: Introduction to Exception Handling and Defensive Programming

Slide 19

Exception Handling Properties All exceptions share similar properties

InnerException property allows the application to store the exception that led up to the current exception

Message property contains a textual message describing the exception

Source property gets the name of the application or object that caused the exception to occur

Page 20: Introduction to Exception Handling and Defensive Programming

Slide 20

Exception Handling Example A simple exception handler

int Current;

try

{

Current = System.Int32.MaxValue + 1

}

Catch (System.Exception ex)

{

MessageBox.Show("Numeric overflow")

}

Page 21: Introduction to Exception Handling and Defensive Programming

Slide 21

Understanding theException Hierarchy The Exception class is hierarchical All exceptions ultimately derive from the System.Exception class

System.SystemException class contains the exceptions defined by the .NET Framework itself

System.IO namespace defines exceptions related to file handling

Organize catch blocks from most specific exception to the most general exception

Page 22: Introduction to Exception Handling and Defensive Programming

Slide 22

Exception Hierarchy

Page 23: Introduction to Exception Handling and Defensive Programming

Slide 23

Exception HandlingStrategy for Applications Four strategies

Ignore the exception, allowing it to propagate automatically up through the call stack

Catch the exception and handle it Catch the exception and re-throw it Divide the exception into two parts. One

part is called the inner exception, and the other is called the outer exception

Page 24: Introduction to Exception Handling and Defensive Programming

Slide 24

The using Keyword (Introduction) Using works in the same way as a block scoped variable

works The variable named declared in the Using statement has

the scope of the Using block Then the block exits, the variable is destroyed along with

any resources the variable is using Example:

using SreamReader = new

StreamReader(“C:\File.txt”)

{

StringVar = sr.ReadToEnd()

}

Page 25: Introduction to Exception Handling and Defensive Programming

Slide 25

The C# Preprocessor A preprocessor conditionally inserts or

omits the code compiled into the program

All preprocessor directives begin with the # character

Page 26: Introduction to Exception Handling and Defensive Programming

Slide 26

The C# Preprocessor (Directives) #if, #else, #elseif are the decision-

making directive You test whether a symbol has been

defined (#define) Logical and relational operators are

supported ==, !=, &&, ||,

Use #define and #undef to define and undefine preprocessor constant

Page 27: Introduction to Exception Handling and Defensive Programming

Slide 27

The C# Preprocessor (Directives) #region #endregion create collapsible

regions #warning, #error throw a compiler

warning or error

Page 28: Introduction to Exception Handling and Defensive Programming

Slide 28

Define Preprocessor Constants (Example)

Page 29: Introduction to Exception Handling and Defensive Programming

Slide 29

Use Preprocessor Constants (Example)

Page 30: Introduction to Exception Handling and Defensive Programming

Slide 30

Page 31: Introduction to Exception Handling and Defensive Programming

Slide 31

#DEBUG and #TRACE These preprocessor directives are

‘special’ They enable and disable debugging and

tracing The can be reset via the application

configuration file

When disabled, the Debug and Trace code is not compiled into the application

Page 32: Introduction to Exception Handling and Defensive Programming

Slide 32

The Debug and Trace Classes Both classes work the same way

One is used to embed debugging code. The other is to used to embed logging code

Write output to Output window Really the default registered “listener”

Test conditions with Assert Create custom listeners

Page 33: Introduction to Exception Handling and Defensive Programming

Slide 33

See frmPreprocessor.cs