Debugging and Handling Exceptions

Similar documents
11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued)

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

After completing this appendix, you will be able to:

Object Oriented Programming Exception Handling

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Introduction to Programming Using Java (98-388)

Visual Studio.NET. Although it is possible to program.net using only the command OVERVIEW OF VISUAL STUDIO.NET

Exception-Handling Overview

Program Correctness and Efficiency. Chapter 2

VB Net Debugging (Console)

Question And Answer.

Error Handling. Exceptions

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Programming II (CS300)

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Introduction to Java

Chapter 11: Exception Handling

Object Oriented Programming

EW The Source Browser might fail to start data collection properly in large projects until the Source Browser window is opened manually.

Chapter 9: Dealing with Errors

Programming II (CS300)

CS159. Nathan Sprague

Exceptions Programming 1 C# Programming. Rob Miles

Exceptions. Exceptions. Exceptional Circumstances 11/25/2013

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Debugging in Small Basic is the process of analysing a program to detect and fix errors or improve functionality in some way.

Introduction. Key features and lab exercises to familiarize new users to the Visual environment

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Std 12 Lesson-10 Exception Handling in Java ( 1

ECE 122. Engineering Problem Solving with Java

Introduction to Computation and Problem Solving

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Computer Science II Lab 3 Testing and Debugging

A Tutorial for ECE 175

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS159. Nathan Sprague

Getting Started (1.8.7) 9/2/2009

1.00 Lecture 2. What s an IDE?

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Under the Debug menu, there are two menu items for executing your code: the Start (F5) option and the

TEMPLATES AND EXCEPTION HANDLING

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Introduction to C/C++ Programming

Using the Xcode Debugger

Lab 8 - Vectors, and Debugging. Directions

Exceptions, Case Study-Exception handling in C++.

About this exam review

CMSC 202. Exceptions

BasicScript 2.25 User s Guide. May 29, 1996

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

6.Introducing Classes 9. Exceptions

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

.Net Technologies. Components of.net Framework

GETTING STARTED WITH ECLIPSE Caitrin Armstrong

Exception handling & logging Best Practices. Angelin

Absolute C++ Walter Savitch

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

The NetBeans Debugger: A Brief Tutorial

Standard. Number of Correlations

Correctness and Robustness

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Programming Logic - Beginning

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4

C16b: Exception Handling

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Outline. Debugging. In Class Exercise Solution. Review If Else If. Immediate Program Errors. Function Test Example

Debugging INTRODUCTION DEBUGGER WHAT IS VBA'S DEBUGGING ENVIRONMENT?

CSC 1214: Object-Oriented Programming

Debug for GDB Users. Action Description Debug GDB $debug <program> <args> >create <program> <args>

Exceptions. CSC207 Winter 2017

7 The Integrated Debugger

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Programming in Visual Basic with Microsoft Visual Studio 2010

Introduction to Java. Handout-3a. cs402 - Spring

mywbut.com Exception Handling

Inheritance & Polymorphism

Exceptions Handeling

Section 1 AVR Studio User Guide

Introduction to Problem Solving and Programming in Python.

BBM 102 Introduction to Programming II Spring Exceptions

JCreator. Starting JCreator

Exceptions and Error Handling

Sahaj Computer Solutions OOPS WITH C++

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++

CS112 Lecture: Exceptions and Assertions

5/19/2015. Objectives. JavaScript, Sixth Edition. Understanding Syntax Errors. Introduction to Debugging. Handling Run-Time Errors

Transcription:

12 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition

Chapter Objectives Learn about exceptions, including how they are thrown and caught Gain an understanding of the different types of errors that are found in programs Look at debugging methods available in Visual Studio Discover how the Debugger can be used to find run-time errors C# Programming: From Problem Analysis to Program Design 2

Chapter Objectives (continued) Become aware of and use exception-handling techniques to include try catch finally clauses Explore the many exception classes and learn how to write and order multiple catch clauses C# Programming: From Problem Analysis to Program Design 3

Errors Visual Studio IDE reports errors as soon as it is able to detect a problem Syntax errors compiler errors Language rule violation Easier to discover and eliminate C# adheres to set of rules known as C# Language Specifications http://msdn.microsoft.com/en-us/library/ms228593.aspx C# Programming: From Problem Analysis to Program Design 4

Errors (continued) Error message does not always state the correct problem Figure 12-1 Syntax error extraneous semicolon C# Programming: From Problem Analysis to Program Design 5

Run-Time Errors Just because your program reports no syntax errors does not necessarily mean it is running correctly One form of run-time error is a logic error Program runs but produces incorrect results May be off-by-one in a loop Sometimes users enter incorrect values Finding the problem can be challenging 6

Debugging in C# Desk check Many IDEs have Debuggers Debuggers let you observe the run-time behavior You can break or halt execution You can step through the application You can evaluate variables You can set breakpoints Debug menu offers debugging options C# Programming: From Problem Analysis to Program Design 7

Debugging in C# (continued) Figure 12-2 Debug menu options C# Programming: From Problem Analysis to Program Design 8

Execution Control Select Start Debugging and the number of options to run your program doubles Figure 12-3 Debug menu options during debugging mode C# Programming: From Problem Analysis to Program Design 9

Breakpoints Markers placed in an application, indicating the program should halt execution when it reaches that point Break mode Examine expressions Check intermediate results Use Debug menu to set Breakpoint F9 (shortcut) Toggles Ctrl + Shift + F9 Clear All Breakpoints C# Programming: From Problem Analysis to Program Design 10

Breakpoints (continued) Red glyph placed on the breakpoint line Figure 12-4 Breakpoint set 11

Break Mode In Break mode, Debugger halts program on the breakpoint line Chapter 5 TicketAppExample Locals window shows all variables and their values Figure 12-5 Locals window at the breakpoint 12

Continue Selecting Continue or F5 causes program to execute from halted line to next breakpoint (or end of Main( ), if no other breakpoints are set Figure 12-6 Next breakpoint C# Programming: From Problem Analysis to Program Design 13

Stepping Through Code Step Into (F11) Step Over (F10) Step Out (Shift+F11) Figure 12-7 Breakpoint location C# Programming: From Problem Analysis to Program Design 14

Stepping Through Code Step Into (F11) Program halts at the first line of code inside the called method Step Over (F10) Executes the entire method called before it halts Step Out (Shift+F11) Causes the rest of the program statements in the method to be executed, and then control returns to the method that made the call- at that point, it halts the program C# Programming: From Problem Analysis to Program Design 15

Watches Can set Watch windows during debugging sessions Watch window lets you type in one or more variables or expressions to observe while the program is running Watch window differs from Locals window, which shows all variables currently in scope Quick Watch option on DEBUG menu lets you type a single variable or expression C# Programming: From Problem Analysis to Program Design 16

Watches (continued) Hover mouse over any variable while in break mode to see its current value Figure 12-8 QuickWatch window C# Programming: From Problem Analysis to Program Design 17

Exceptions Can take several actions to keep your program from crashing Prior to parsing, include if statements that check values used as input if (char.isnumber(avalue[0])) // Tests the first character Use string s Length property to create a loop Use if statement to make sure divisors are not zero Test subscript or index values used with arrays to make sure they are valid and nonnegative C# Programming: From Problem Analysis to Program Design 18

Actions to Keep Program from Crashing (continued) Test subscript or index values used with arrays to make sure they are one less than the dimensioned size With Windows applications, test input controls, such as text boxes, for empty string input When working with files, make sure the file exists prior to attempting to retrieve values Test numeric values for valid ranges prior to using the number in arithmetic C# Programming: From Problem Analysis to Program Design 19

Exceptions Some circumstances are beyond programmer s control You have assumed nothing unusual would occur Have probably experienced unhandled exceptions being thrown While you browsed Web pages While you were developing applications using C# Unless provisions are made for handling exceptions, your program may crash or produce erroneous results Unhandled exception 20

Exceptions (continued) Dialog box asks you whether you want to have an error report sent to Microsoft Figure 12-9 Microsoft error reporting C# Programming: From Problem Analysis to Program Design 21

Exceptions (continued) Normally you do not want to try to debug application while it is running Figure 12-10 Just-In-Time Debugger Click No C# Programming: From Problem Analysis to Program Design 22

Unhandled Exception Message displayed when you are creating console application and unhandled exception occurs Figure 12-11 Unhandled exception in a console application C# Programming: From Problem Analysis to Program Design 23

Unhandled Exception (continued) Selecting Debug>Start to run application in Visual Studio Yellow arrow marks the error (erroneous code highlighted) Figure 12-12 Unhandled exception thrown dividing by zero C# Programming: From Problem Analysis to Program Design 24

Raising an Exception Error encountered no recovery Raise or throw an exception Execution halts in the current method and the Common Language Runtime (CLR) attempts to locate an exception handler Exception handler: block of code to be executed when a certain type of error occurs If no exception handler is found in current method, exception is thrown back to the calling method C# Programming: From Problem Analysis to Program Design 25

Bugs, Errors, and Exceptions Bugs differ from exceptions Bugs, also called "programmer mistakes," should be caught and fixed before application released Errors can be created because of user actions Example Entering wrong type of data produces unhandled exception when ParseInt( ) called Details button in Visual Studio lists a stack trace of methods with the method that raised the exception listed first 26

Bugs, Errors, and Exceptions (continued) Stack trace Figure 12-13 Unhandled exception raised by incorrect input string C# Programming: From Problem Analysis to Program Design 27

Exception-Handling Techniques If event creates a problem frequently, best to use conditional expressions to catch and fix problem Execution is slowed down when CLR has to halt a method and find an appropriate event handler Exception-handling techniques are for serious errors that occur infrequently Exceptions classes integrated within the FCL Used with the try catch finally program constructs Common Language Runtime (CLR) Framework Class Library (FCL) 28

Try Catch Finally Blocks Code that may create a problem is placed in the try block Code to deal with the problem (the exception handler) is placed in catch blocks Code to be executed whether an exception is thrown or not is placed in the finally block C# Programming: From Problem Analysis to Program Design 29

try { } // Statements catch [ (ExceptionClassName exceptionidentifier) ] { } // Exception handler statements : // [additional catch clauses] [ finally { } ] // Statements Notice square brackets indicate optional entry One catch clause required finally clause optional C# Programming: From Problem Analysis to Program Design 30

Try Catch Finally Blocks Generic catch clause (continued) Omit argument list with the catch Any exception thrown is handled by executing code within that catch block Control is never returned into the try block after an exception is thrown Using a try catch block can keep the program from terminating abnormally 31

Use of Generic Catch Clause Example 12-2 uses a generic catch block Figure 12-14 Generic catch block handles the exception C# Programming: From Problem Analysis to Program Design 32

// calculate average grade for a class int totalgrades = 0; int grade = 0; int sumgrades = 0; String data = ""; Console.WriteLine("Please enter a grade [## to end]"); while (true) { try { data = Console.ReadLine(); grade = int.parse(data); sumgrades += grade; totalgrades++; } catch (Exception e) { if (data == "##") break; Console.WriteLine("Invalid data - try again"); } } Console.WriteLine("Please enter a grade [## to end]"); if (totalgrades > 0) Console.WriteLine("Average grade is {0:F2}", sumgrades / totalgrades); else Console.WriteLine("Average = 0 (No data was supplied)"); 33

Use of Generic Catch Clause (continued) catch { Console.WriteLine("Problem with scores - " + "Cannot compute average"); } Any type of exception is handled by the generic catch C# Programming: From Problem Analysis to Program Design 34

What Caused These Exceptions to be Thrown? Never quite sure what causes the exception to be thrown when a generic catch clause is used! Figure 12-15 Exceptions division by zero and programmer errors C# Programming: From Problem Analysis to Program Design 35

Exception Object When an exception is raised, an object is created Object has properties and behaviors (methods) Catch clause may list an exception class Catch { } without exception type does not give you access to an object Base exception class: Exception Message property returns a string describing exception StackTrace property returns a string that contains the called trace of methods 36

Use of Generic Catch Clause (continued) catch (System.Exception e) No filtering of exceptions occurs with (System.Exception e) for the argument list Any exception that is thrown in this method is caught because all exceptions are derived from this base System.Exception class C# Programming: From Problem Analysis to Program Design 37

Exception Object (continued) catch (System.Exception e) { Console.Error.WriteLine("Problem with scores - " + "Can not compute average"); Console.Error.WriteLine(e.Message); } Message property lists what exception was thrown Figure 12-16 Use of Message property with the exception object 38

Exception Classes ApplicationException and SystemException classes form the basis for run-time exceptions Table 12-1 Derived classes of the base Exception class 39

Exception Classes (continued) ApplicationException Derive from this class when you write your own exception classes User program must throw the exception, not the CLR SystemException Most run-time exceptions derive from this class SystemException class adds no functionality to classes; includes no additional properties or methods 40

SystemException Class More than 70 classes derived from SystemException Table 12-2 Derived classes of the SystemException class C# Programming: From Problem Analysis to Program Design 41

SystemException Class (continued) Table 12-2 Derived classes of the SystemException class (continued) C# Programming: From Problem Analysis to Program Design 42

System.DivideByZeroException Derived class of System.ArithmeticException class Thrown when an attempt to divide by zero occurs Only thrown for integral or integer data types Floating-point operands do not throw an exception Result reported as either positive infinity, negative infinity, or Not-a-Number (NaN) Follows the rules from IEEE 754 arithmetic C# Programming: From Problem Analysis to Program Design 43

Filtering Multiple Exceptions Can include multiple catch clauses Order of placement is important Enables writing code specific to thrown exception Review MultipleCatches Example C# Programming: From Problem Analysis to Program Design 44

Filtering Multiple Exceptions Place catch clauses from most specific to most generic If Exception class is included, it should always be placed last try {// statements omitted } catch (System.FormatException e) { // statements omitted} catch (System.DivideByZeroException e) { // statements omitted} catch (System.ArithmeticException e) { // statements omitted} catch (System.Exception e) { // statements omitted} finally { // statements omitted} 45

Filtering Multiple Exceptions (continued) Figure 12-7 Number FormatException thrown Figure 12-8 DivideByZero exception thrown C# Programming: From Problem Analysis to Program Design 46

Filtering Multiple Exceptions (continued) averagetestscore = (double)totalscores / countofscores; Figure 12-19 Floating-point division by zero C# Programming: From Problem Analysis to Program Design 47

Custom Exceptions Derive from the ApplicationException class Good idea to use the word Exception as part of the identifier Creating an exception class is no different from creating any other class C# Programming: From Problem Analysis to Program Design 48

Custom Exceptions (continued) public class FloatingPtDivisionException : System.ApplicationException { String public FloatingPtDivisionException argument sent (string exceptiontype) to the base : base (exceptiontype) constructor { indicating type // Empty body of exception } } C# Programming: From Problem Analysis to Program Design 49

Userdefined class public class TestOfCustomException { static void Main(string[ ] args) { double value1 = 0, value2=0, answer; try { //Could include code to enter new values. answer = GetResults(value1, value2); } catch (FloatingPtDivisionException excepobj) { Console.Error.WriteLine(excepObj.Message); } catch { Console.Error.WriteLine("Something else " + } } "happened!"); C# Programming: From Problem Analysis to Program Design 50

Throwing an Exception Exception object is instantiated when an exceptional condition occurs Can be any condition, but should be one that happens infrequently After object is instantiated, object is thrown Exception is thrown by the program using the throw keyword C# Programming: From Problem Analysis to Program Design 51

static double GetResults (double value1, double value2) { if (value2 <.0000001) // Be careful comparing floating- // point values for equality. { FloatingPtDivisionException excepobj = new FloatingPtDivisionException ("Exception type: " + "Floating-point division by zero"); throw excepobj; } } return value1 / value2; } Throwing an exception C# Programming: From Problem Analysis to Program Design 52

Custom Exceptions (continued) Figure 12-20 TestOfCustomException threw FloatingPtDivisionException exception C# Programming: From Problem Analysis to Program Design 53

Input Output (IO) Exceptions System.IO.IOException Direct descendent of Exception Thrown when a specified file or directory is not found Thrown when program attempts to read beyond the end of a file Thrown when there are problems loading or accessing the contents of a file C# Programming: From Problem Analysis to Program Design 54

Input Output (IO) Exceptions (continued) Table 12-3 Derived classes of IO.IOException C# Programming: From Problem Analysis to Program Design 55

ICW WaterDepth Application Figure 12-21 Problem specification for WaterDepth application C# Programming: From Problem Analysis to Program Design 56

ICW WaterDepth Application (continued) Table 12-4 ShoalArea class data fields C# Programming: From Problem Analysis to Program Design 57

ICW WaterDepth Application (continued) Figure 12-22 Prototype for WaterDepth input form Figure 12-23 Prototype for WaterDepth final output C# Programming: From Problem Analysis to Program Design 58

ICW WaterDepth Application (continued) Figure 12-24 Class diagrams for WaterDepth application C# Programming: From Problem Analysis to Program Design 59

ICW WaterDepth Application (continued) Figure 12-25 Behavior for the FrmWaterDepth class C# Programming: From Problem Analysis to Program Design 60

ICW WaterDepth Application (continued) Figure 12-26 Behavior of the ShoalArea class C# Programming: From Problem Analysis to Program Design 61

ICW WaterDepth Application (continued) Table 12-5 WaterDepth property values C# Programming: From Problem Analysis to Program Design 62

ICW WaterDepth Application (continued) Table 12-5 WaterDepth property values (continued) C# Programming: From Problem Analysis to Program Design 63

ICW WaterDepth Application (continued) Table 12-5 WaterDepth property values (continued) C# Programming: From Problem Analysis to Program Design 64

ICW WaterDepth Application (continued) Figure 12-27 FrmWaterDepth form C# Programming: From Problem Analysis to Program Design 65

ICW WaterDepth Application (continued) Figure 12-28 WaterDepth application output C# Programming: From Problem Analysis to Program Design 66

ICW WaterDepth Application (continued) Figure 12-29 State exception thrown Figure 12-30 Invalid input exception C# Programming: From Problem Analysis to Program Design 67

ICW WaterDepth Application (continued) Figure 12-31 Debug information sent to Output window C# Programming: From Problem Analysis to Program Design 68

Coding Standards Avoid using exception-handling techniques to deal with problems that can be handled with reasonable coding effort Encapsulating all methods in a try...catch block hampers performance Order exceptions from the most specific to the least specific Add Exception onto the end of the name for custom classes C# Programming: From Problem Analysis to Program Design 69

Resources The C# Corner - Exception-Handling articles http://www.c-sharpcorner.com/ msdn Exceptions and Exception Handling (C# Programming Guide) http://msdn.microsoft.com/en-us/library/ms173160.aspx CSharpFriends - Exception Handling in C# http://www.csharpfriends.com/articles/getarticle.aspx?article ID=128 CodeGuru - Error Handling http://www.codeguru.com/csharp/csharp/cs_syntax/errorhand ling/ C# Programming: From Problem Analysis to Program Design 70

Chapter Summary Types of errors Debugger Halt execution to examine code Breakpoints Locals window shows variables in scope Step Into, Step Over, and Step Out Exceptions Unexpected conditions Abnormal termination if not handled C# Programming: From Problem Analysis to Program Design 71

Chapter Summary (continued) Exceptions How to throw and catch exceptions Exception-handling techniques try catch finally clauses Exception object Exception classes Application Exception SystemException C# Programming: From Problem Analysis to Program Design 72

Chapter Summary (continued) Generic catch clauses Filter multiple catch clauses Placement of catch clauses Create custom Exception classes Throw exception Input Output Exceptions C# Programming: From Problem Analysis to Program Design 73