Module 4: Statements and Exceptions. Overview Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Introduction to C Programming
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
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.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
C++ for Engineers and Scientists Third Edition
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Introduction to Exception Handling and Defensive Programming.
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.
ISBN Chapter 8 Statement-Level Control Structures.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
April 16, ICE 1341 – Programming Languages (Lecture #14) In-Young Ko Programming Languages (ICE 1341) Lecture #14 Programming Languages (ICE 1341)
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
CIS 3301 C# Lesson 3 Control Statements - Selection.
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.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
CS 161 Introduction to Programming and Problem Solving Chapter 18 Control Flow Through C++ Program Herbert G. Mayer, PSU Status 10/8/2014 Initial content.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 8 Java Fundamentals Control Structures Fri.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
W E E K F I V E Control Flow. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements Iterative Statements.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
JavaScript and Ajax (Control Structures) Week 4 Web site:
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
LOOPS CHAPTER Topics  Four Types of Loops –while –do…while –for –foreach  Jump Statements in Loops –break –continue 2.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
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.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
Eighth Lecture Exception Handling in Java
Chapter 8: Control Structures
Haidong Xue Summer 2011, at GSU
Conditional Statements
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
By Hector M Lugo-Cordero September 3, 2008
CHAPTER 21 LOOPS 1.
Introduction to Programming
CSC215 Lecture Control Flow.
Presentation transcript:

Module 4: Statements and Exceptions

Overview Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling Basic Exceptions Raising Exceptions

Introduction to Statements Statement Blocks Types of Statements

Statement Blocks Use braces As block delimiters { // code } { // code } { int i;... { int i;... } { int i;... { int i;... } { int i;... }... { int i;... } { int i;... }... { int i;... } A block and its parent block cannot have a variable with the same name Sibling blocks can have variables with the same name

Types of Statements Selection Statements The if and switch statements Selection Statements The if and switch statements Iteration Statements The while, do, for, and foreach statements Iteration Statements The while, do, for, and foreach statements Jump Statements The goto, break, and continue statements Jump Statements The goto, break, and continue statements

Using Selection Statements The if Statement Cascading if Statements The switch Statement Quiz: Spot the Bugs

The if Statement Syntax: No implicit conversion from int to bool int x;... if (x)... // Must be if (x != 0) in C# if (x = 0)... // Must be if (x == 0) in C# int x;... if (x)... // Must be if (x != 0) in C# if (x = 0)... // Must be if (x == 0) in C# if ( Boolean-expression ) first-embedded-statement else second-embedded-statement if ( Boolean-expression ) first-embedded-statement else second-embedded-statement

Cascading if Statements enum Suit { Clubs, Hearts, Diamonds, Spades } Suit trumps = Suit.Hearts; if (trumps == Suit.Clubs) color = "Black"; else if (trumps == Suit.Hearts) color = "Red"; else if (trumps == Suit.Diamonds) color = "Red"; else color = "Black"; enum Suit { Clubs, Hearts, Diamonds, Spades } Suit trumps = Suit.Hearts; if (trumps == Suit.Clubs) color = "Black"; else if (trumps == Suit.Hearts) color = "Red"; else if (trumps == Suit.Diamonds) color = "Red"; else color = "Black";

The switch Statement Use switch statements for multiple case blocks Use break statements to ensure that no fall through occurs switch (trumps) { case Suit.Clubs : case Suit.Spades : color = "Black"; break; case Suit.Hearts : case Suit.Diamonds : color = "Red"; break; default: color = "ERROR"; break; } switch (trumps) { case Suit.Clubs : case Suit.Spades : color = "Black"; break; case Suit.Hearts : case Suit.Diamonds : color = "Red"; break; default: color = "ERROR"; break; }

Quiz: Spot the Bugs if number % 2 == 0... if (percent 100)... if (minute == 60); minute = 0; if (minute == 60); minute = 0; switch (trumps) { case Suit.Clubs, Suit.Spades : color = "Black"; case Suit.Hearts, Suit.Diamonds : color = "Red"; defualt :... } switch (trumps) { case Suit.Clubs, Suit.Spades : color = "Black"; case Suit.Hearts, Suit.Diamonds : color = "Red"; defualt :... }

Using Iteration Statements The while Statement The do Statement The for Statement The foreach Statement Quiz: Spot the Bugs

The while Statement Execute embedded statements based on Boolean value Evaluate Boolean expression at beginning of loop Execute embedded statements while Boolean value Is True int i = 0; while (i < 10) { Console.WriteLine(i); i++; } int i = 0; while (i < 10) { Console.WriteLine(i); i++; }

The do Statement Execute embedded statements based on Boolean value Evaluate Boolean expression at end of loop Execute embedded statements while Boolean value Is True int i = 0; do { Console.WriteLine(i); i++; } while (i < 10); int i = 0; do { Console.WriteLine(i); i++; } while (i < 10);

The for Statement Place update information at the start of the loop Variables in a for block are scoped only within the block A for loop can iterate over several values for (int i = 0; i < 10; i++) { Console.WriteLine(i); } for (int i = 0; i < 10; i++) { Console.WriteLine(i); } for (int i = 0; i < 10; i++) Console.WriteLine(i); Console.WriteLine(i); // Error: i is no longer in scope for (int i = 0; i < 10; i++) Console.WriteLine(i); Console.WriteLine(i); // Error: i is no longer in scope for (int i = 0, j = 0;... ; i++, j++)

The foreach Statement Choose the type and name of the iteration variable Execute embedded statements for each element of the collection class ArrayList numbers = new ArrayList( ); for (int i = 0; i < 10; i++ ) { numbers.Add(i); } foreach (int number in numbers) { Console.WriteLine(number); } ArrayList numbers = new ArrayList( ); for (int i = 0; i < 10; i++ ) { numbers.Add(i); } foreach (int number in numbers) { Console.WriteLine(number); }

Quiz: Spot the Bugs for (int i = 0, i < 10, i++) Console.WriteLine(i); for (int i = 0, i < 10, i++) Console.WriteLine(i); int i = 0; while (i < 10) Console.WriteLine(i); int i = 0; while (i < 10) Console.WriteLine(i); for (int i = 0; i >= 10; i++) Console.WriteLine(i); for (int i = 0; i >= 10; i++) Console.WriteLine(i); do... string line = Console.ReadLine( ); guess = int.Parse(line); while (guess != answer); do... string line = Console.ReadLine( ); guess = int.Parse(line); while (guess != answer);

Using Jump Statements The goto Statement The break and continue Statements

The goto Statement Flow of control transferred to a labeled statement Can easily result in obscure spaghetti code if (number % 2 == 0) goto Even; Console.WriteLine("odd"); goto End; Even: Console.WriteLine("even"); End:; if (number % 2 == 0) goto Even; Console.WriteLine("odd"); goto End; Even: Console.WriteLine("even"); End:;

The break and continue Statements The break statement jumps out of an iteration The continue statement jumps to the next iteration int i = 0; while (true) { Console.WriteLine(i); i++; if (i < 10) continue; else break; } int i = 0; while (true) { Console.WriteLine(i); i++; if (i < 10) continue; else break; }

Lab 4.1: Using Statements

Handling Basic Exceptions Why Use Exceptions? Exception Objects Using try and catch Blocks Multiple catch Blocks

Why Use Exceptions? Traditional procedural error handling is cumbersome int errorCode = 0; FileInfo source = new FileInfo("code.cs"); if (errorCode == -1) goto Failed; int length = (int)source.Length; if (errorCode == -2) goto Failed; char[] contents = new char[length]; if (errorCode == -3) goto Failed; // Succeeded... Failed:... int errorCode = 0; FileInfo source = new FileInfo("code.cs"); if (errorCode == -1) goto Failed; int length = (int)source.Length; if (errorCode == -2) goto Failed; char[] contents = new char[length]; if (errorCode == -3) goto Failed; // Succeeded... Failed:... Error handling Core program logic

Exception Objects Exception SystemException OutOfMemoryException IOException NullReferenceException ApplicationException

Using try and catch Blocks Object-oriented solution to error handling Put the normal code in a try block Handle the exceptions in a separate catch block try { Console.WriteLine("Enter a number"); int i = int.Parse(Console.ReadLine()); } catch (OverflowException caught) { Console.WriteLine(caught); } try { Console.WriteLine("Enter a number"); int i = int.Parse(Console.ReadLine()); } catch (OverflowException caught) { Console.WriteLine(caught); } Error handling Program logic

Multiple catch Blocks Each catch block catches one class of exception A try block can have one general catch block A try block is not allowed to catch a class that is derived from a class caught in an earlier catch block try { Console.WriteLine("Enter first number"); int i = int.Parse(Console.ReadLine()); Console.WriteLine("Enter second number"); int j = int.Parse(Console.ReadLine()); int k = i / j; } catch (OverflowException caught) {…} catch (DivideByZeroException caught) {…} try { Console.WriteLine("Enter first number"); int i = int.Parse(Console.ReadLine()); Console.WriteLine("Enter second number"); int j = int.Parse(Console.ReadLine()); int k = i / j; } catch (OverflowException caught) {…} catch (DivideByZeroException caught) {…}

Raising Exceptions The throw Statement The finally Clause Checking for Arithmetic Overflow Guidelines for Handling Exceptions

The throw Statement Throw an appropriate exception Give the exception a meaningful message throw expression ; if (minute = 60) { throw new InvalidTimeException(minute + " is not a valid minute"); // !! Not reached !! } if (minute = 60) { throw new InvalidTimeException(minute + " is not a valid minute"); // !! Not reached !! }

The finally Clause All of the statements in a finally block are always executed Monitor.Enter(x); try {... } finally { Monitor.Exit(x); } Monitor.Enter(x); try {... } finally { Monitor.Exit(x); } Any catch blocks are optional

Checking for Arithmetic Overflow By default, arithmetic overflow is not checked A checked statement turns overflow checking on checked { int number = int.MaxValue; Console.WriteLine(++number); } checked { int number = int.MaxValue; Console.WriteLine(++number); } unchecked { int number = int.MaxValue; Console.WriteLine(++number); } unchecked { int number = int.MaxValue; Console.WriteLine(++number); } OverflowException Exception object is thrown. WriteLine is not executed. MaxValue + 1 is negative?

Guidelines for Handling Exceptions Throwing Avoid exceptions for normal or expected cases Never create and throw objects of class Exception Include a description string in an Exception object Throw objects of the most specific class possible Catching Arrange catch blocks from specific to general Do not let exceptions drop off Main

Lab 4.2: Using Exceptions

Review Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling Basic Exceptions Raising Exceptions