32
Module 4: Statements and Exceptions

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

Embed Size (px)

Citation preview

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

Module 4: Statements and Exceptions

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

Overview

Introduction to Statements

Using Selection Statements

Using Iteration Statements

Using Jump Statements

Handling Basic Exceptions

Raising Exceptions

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

Introduction to Statements

Statement Blocks

Types of Statements

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

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

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

Types of Statements

Selection Statements The if and switch statementsSelection Statements The if and switch statements

Iteration Statements The while, do, for, and foreach statementsIteration Statements The while, do, for, and foreach statements

Jump Statements The goto, break, and continue statementsJump Statements The goto, break, and continue statements

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

Using Selection Statements

The if Statement

Cascading if Statements

The switch Statement

Quiz: Spot the Bugs

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

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-statementelse second-embedded-statement

if ( Boolean-expression ) first-embedded-statementelse second-embedded-statement

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

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";

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

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;}

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

Quiz: Spot the Bugs

if number % 2 == 0 ...if number % 2 == 0 ...

if (percent < 0) || (percent > 100) ...if (percent < 0) || (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 : ...}

2222

3333

4444

1111

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

Using Iteration Statements

The while Statement

The do Statement

The for Statement

The foreach Statement

Quiz: Spot the Bugs

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

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++;}

0 1 2 3 4 5 6 7 8 9

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

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);

0 1 2 3 4 5 6 7 8 9

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

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

0 1 2 3 4 5 6 7 8 9

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++)for (int i = 0, j = 0; ... ; i++, j++)

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

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

0 1 2 3 4 5 6 7 8 9

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

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);

2222

3333

4444

1111

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

Using Jump Statements

The goto Statement

The break and continue Statements

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

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:;

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

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;}

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

Lab 4.1: Using Statements

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

Handling Basic Exceptions

Why Use Exceptions?

Exception Objects

Using try and catch Blocks

Multiple catch Blocks

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

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 handlingError handling

Core program logicCore program logic

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

Exception Objects

ExceptionException

SystemExceptionSystemException

OutOfMemoryExceptionOutOfMemoryException

IOExceptionIOException

NullReferenceExceptionNullReferenceException

ApplicationExceptionApplicationException

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

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 handlingError handling

Program logicProgram logic

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

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) {…}

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

Raising Exceptions

The throw Statement

The finally Clause

Checking for Arithmetic Overflow

Guidelines for Handling Exceptions

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

The throw Statement

Throw an appropriate exception

Give the exception a meaningful message

throw expression ;throw expression ;

if (minute < 1 || minute >= 60) { throw new InvalidTimeException(minute + " is not a valid minute"); // !! Not reached !!}

if (minute < 1 || minute >= 60) { throw new InvalidTimeException(minute + " is not a valid minute"); // !! Not reached !!}

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

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 optionalAny catch blocks are optional

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

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);} -2147483648

OverflowExceptionOverflowException

Exception object is thrown. WriteLine is not executed.

MaxValue + 1 is negative?

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

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

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

Lab 4.2: Using Exceptions

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

Review

Introduction to Statements

Using Selection Statements

Using Iteration Statements

Using Jump Statements

Handling Basic Exceptions

Raising Exceptions