Introduction to Exception Handling and Defensive Programming.

Slides:



Advertisements
Similar presentations
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Advertisements

Error-handling using exceptions
Topics Introduction Types of Errors Exceptions Exception Handling
Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Chapter 15 Strings String::Concat String::CompareTo, Equals, == If( string1 == S”Hello”) String1->Equals(S”Hello”) String1->CompareTo(S”Hello”) CompareTo.
Finding and Debugging Errors
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
Slides Credit Umair Javed LUMS Web Application Development.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Programming Pillars Introduction to Object- Oriented Programming.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
Java Programming: Guided Learning with Early Objects
VB.Net - Exceptions Copyright © Martin Schray
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
CNS 3260 C# .NET Software Development
Part B – Structured Exception Handling
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

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

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

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

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.”

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

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

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

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

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

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

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

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

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

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

Slide 16 Control Flow of Exceptions

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

Slide 18 Propagating Exceptions Illustration (VB)

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

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") }

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

Slide 22 Exception Hierarchy

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

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() }

Slide 25 The C# Preprocessor A preprocessor conditionally inserts or omits the code compiled into the program All preprocessor directives begin with the # character

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

Slide 27 The C# Preprocessor (Directives) #region #endregion create collapsible regions #warning, #error throw a compiler warning or error

Slide 28 Define Preprocessor Constants (Example)

Slide 29 Use Preprocessor Constants (Example)

Slide 30

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

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

Slide 33 See frmPreprocessor.cs