Download presentation
Presentation is loading. Please wait.
Published byAshley Burke Modified over 9 years ago
1
Introduction to Exception Handling and Defensive Programming
2
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
3
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
4
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
5
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.”
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
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
15
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
16
Slide 16 Control Flow of Exceptions
17
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
18
Slide 18 Propagating Exceptions Illustration (VB)
19
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
20
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") }
21
Slide 21 Understanding the Exception 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
22
Slide 22 Exception Hierarchy
23
Slide 23 Exception Handling Strategy 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
24
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() }
25
Slide 25 The C# Preprocessor A preprocessor conditionally inserts or omits the code compiled into the program All preprocessor directives begin with the # character
26
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
27
Slide 27 The C# Preprocessor (Directives) #region #endregion create collapsible regions #warning, #error throw a compiler warning or error
28
Slide 28 Define Preprocessor Constants (Example)
29
Slide 29 Use Preprocessor Constants (Example)
30
Slide 30
31
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
32
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
33
Slide 33 See frmPreprocessor.cs
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.