Top Banner
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET
47

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

Jan 18, 2018

Download

Documents

Stewart Curtis

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 3 Errors and Exceptions Overview Looking at the exception classes Using try – catch – finally to capture exceptions Creating user-defined exceptions
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

1

Programming in C#.NET

Page 2: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

2

Outline

1. Errors and Exceptions

2. Looking Into Errors And Exception Handling

Lecture 8 – C# Basics VIII

Page 3: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

3

Errors and ExceptionsOverview

• Looking at the exception classes• Using try – catch – finally to capture

exceptions• Creating user-defined exceptions

Page 4: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

4

Looking Into Errors And Exception Handling

• Exception Classes

Page 5: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

5

Base class exception classes

Page 6: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

6

Base class exception classes

• System.SystemException • System.ApplicationException • StackOverflowException • EndOfStreamException • OverflowException

Page 7: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

7

Catching Exceptions

• try blocks - the code might encounter some serious error conditions.

• catch blocks - the code that deals with the various error conditions.

• finally blocks - the code that cleans up any resources or takes any other action that you will normally want done at the end of a try or catch block.

Page 8: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

8

Catching Exceptions

1. The execution flow first enters the try block.2. If no errors occur in the try block, execution

proceeds normally through the block, and when the end of the try block is reached, the flow of execution jumps to the finally block if one is present (Step 5). However, if an error does occur within the try block, execution jumps to a catch block (next step).

3. The error condition is handled in the catch block.4. At the end of the catch block, execution

automatically transfers to the finally block if one is present.

5. The finally block is executed.

Page 9: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

9

Catching Exceptions

try{// code for normal execution}catch {// error handling}finally{// clean up}

Page 10: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

10

Catching Exceptions

• You can omit the finally block because it is optional.

• You can also supply as many catch blocks as you want to handle specific types of errors.

• You can omit the catch blocks altogether, in which case the syntax serves not to identify exceptions, but as a way of guaranteeing that code in the finally block will be executed when execution leaves the try block. This is useful if the try block contains several exit points.

Page 11: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

11

Catching Exceptions

throw new OverflowException();

catch (OverflowException ex){// exception handling here}

Page 12: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

12

Catching Exceptions

try {// code for normal execution

if (Overflow == true)throw new OverflowException();

// more processing

if (OutOfBounds == true)throw new IndexOutOfRangeException();

// otherwise continue normal execution}catch (OverflowException ex){// error handling for the overflow error condition}catch (IndexOutOfRangeException ex){// error handling for the index out of range error condition}finally{// clean up}

Page 13: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

13

Implementing multiple catch blocks

using System;

namespace Wrox.ProCSharp.AdvancedCSharp{public class MainEntryPoint{public static void Main(){string userInput;while (true){try{Console.Write("Input a number between 0 and 5 " +"(or just hit return to exit)> ");userInput = Console.ReadLine();if (userInput == "")break;int index = Convert.ToInt32(userInput);if (index < 0 || index > 5)throw new IndexOutOfRangeException("You typed in " + userInput);Console.WriteLine("Your number was " + index);

Page 14: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

14

Implementing multiple catch blocks

}catch (IndexOutOfRangeException ex){Console.WriteLine("Exception: " +"Number should be between 0 and 5. " + ex.Message);}catch (Exception ex){Console.WriteLine("An exception was thrown. Message was: " + ex.Message);}catch{Console.WriteLine("Some other exception has occurred");}finally{Console.WriteLine("Thank you");}}}}}

Page 15: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

15

Implementing multiple catch blocks

if (index < 0 || index > 5) throw new IndexOutOfRangeException("You typed in " + userInput);

Page 16: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

16

Implementing multiple catch blocks

catch (IndexOutOfRangeException ex){ Console.WriteLine( "Exception: Number should be between 0 and 5." + ex.Message);

}

Page 17: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

17

Implementing multiple catch blocks

catch (Exception ex){ Console.WriteLine("An exception was thrown. Message was: " + ex.Message);

}

Page 18: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

18

Implementing multiple catch blocks

catch{ Console.WriteLine("Some other exception has occurred");

}

Page 19: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

19

Implementing multiple catch blocks

Input a number between 0 and 5 (or just hit return to exit)> 4Your number was 4Thank youInput a number between 0 and 5 (or just hit return to exit)> 0Your number was 0Thank youInput a number between 0 and 5 (or just hit return to exit)>

10Exception: Number should be between 0 and 5. You typed in 10Thank youInput a number between 0 and 5 (or just hit return to exit)>

helloAn exception was thrown. Message was: Input string was not in

a correct format.Thank youInput a number between 0 and 5 (or just hit return to exit)>Thank you

Page 20: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

20

Catching exceptions from other code

• IndexOutOfRangeException, thrown by your own code.

• FormatException, thrown from inside one of the base classes.

Page 21: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

21

System.Exception properties

Data This provides you with the ability to add key/value statements to the excep-

tion that can be used to supply extra information about the exception. This is a new property in the .NET Framework 2.0.

HelpLink This is a link to a help file that provides more information about the

exception. InnerException If this exception was thrown inside a catch block, then InnerException

contains the exception object that sent the code into that catch block. Message This is text that describes the error condition. Source This is the name of the application or object that caused the exception. StackTrace This provides details of the method calls on the stack (to help track down the

method that threw the exception). TargetSite This is a .NET reflection object that describes the method that threw the

exception.

Page 22: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

22

System.Exception properties

if (ErrorCondition == true){Exception myException = new ClassmyException("Help!!!!");

myException.Source = "My Application Name";

myException.HelpLink = "MyHelpFile.txt";myException.Data["ErrorDate"] = DateTime.Now;

myException.Data.Add("AdditionalInfo", "Contact Bill from the Blue Team");

throw myException;}

Page 23: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

23

What happens if an exception isn't handled?

• FormatException • IndexOutOfRangeExceptionThe answer is that the .NET runtime would catch

it.

Page 24: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

24

Nested try blocks

try {

// Point Atry{

// Point B}catch{

// Point C}finally{

// clean up} // Point D

}catch{

// error handling}finally{

// clean up}

Page 25: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

25

Nested try blocks

• Important It is perfectly legitimate to throw exceptions from catch and finally blocks.

Page 26: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

26

Nested try blocks

• To modify the type of exception thrown• To enable different types of exception to be

handled in different places in your code

Page 27: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

27

User-Defined Exception Classes

• The user might type the name of a file that doesn't exist. This will be caught as a FileNotFound exception.

• The file might not be in the correct format. There are two possible problems here. First, the first line of the file might not be an integer. Second, there might not be as many names in the file as the first line of the file indicates. In both cases, you want to trap this oddity as a custom exception that has been written specially for this purpose, ColdCallFileFormatException.

Page 28: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

28

User-Defined Exception Classes

4George WashingtonZbigniew HarlequinJohn AdamsThomas Jefferson

Page 29: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

29

User-Defined Exception Classes

• The user might type the name of a file that doesn't exist. FileNotFound exception.

• The file might not be in the correct format. 1. the first line of the file might not be an integer. 2. there might not be as many names in the file as the first

line of the file indicates.

ColdCallFileFormatException.

Page 30: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

30

Catching the user-defined exceptions

using System;using System.IO;

namespace Wrox.ProCSharp.AdvancedCSharp{class MainEntryPoint{static void Main(){string fileName;Console.Write("Please type in the name of

the file " +"containing the names of the people to be

cold-called > ");

Page 31: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

31

Catching the user-defined exceptions

fileName = Console.ReadLine();ColdCallFileReader peopleToRing = new

ColdCallFileReader();

try{peopleToRing.Open(fileName);for (int i=0 ; i<peopleToRing.NPeopleToRing; i++){peopleToRing.ProcessNextPerson();}Console.WriteLine("All callers processed

correctly");}

Page 32: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

32

Catching the user-defined exceptions

catch(FileNotFoundException ex){Console.WriteLine("The file {0} does not exist",

fileName);}catch(ColdCallFileFormatException ex){Console.WriteLine("The file {0} appears to have been corrupted",

fileName);Console.WriteLine("Details of problem are: {0}",

ex.Message);if (ex.InnerException != null)Console.WriteLine("Inner exception was: {0}",

ex.InnerException.Message);

Page 33: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

33

Catching the user-defined exceptions

}catch(Exception ex){Console.WriteLine("Exception occurred:\n"

+ ex.Message);}finally{peopleToRing.Dispose();}Console.ReadLine();}}

Page 34: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

34

Throwing the user-defined exceptions

class ColdCallFileReader :IDisposable

{FileStream fs;StreamReader sr;uint nPeopleToRing;bool isDisposed = false;bool isOpen = false;

Page 35: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

35

Throwing the user-defined exceptions

public void Open(string fileName){if (isDisposed)throw new ObjectDisposedException("peopleToRing");fs = new FileStream(fileName, FileMode.Open);sr = new StreamReader(fs);try {string firstLine = sr.ReadLine();nPeopleToRing = uint.Parse(firstLine);isOpen = true;}catch (FormatException ex){throw new ColdCallFileFormatException("First line isn\'t}}

Page 36: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

36

Throwing the user-defined exceptions

public void ProcessNextPerson(){if (isDisposed)throw new

ObjectDisposedException("peopleToRing");if (!isOpen)throw new UnexpectedException("Attempted to access cold call file that is not

open");try{string name;name = sr.ReadLine();if (name == null)throw new ColdCallFileFormatException("Not enough

names");if (name[0] == 'Z')

Page 37: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

37

Throwing the user-defined exceptions

{throw new LandLineSpyFoundException(name);}Console.WriteLine(name);}catch(LandLineSpyFoundException ex){Console.WriteLine(ex.Message);}

finally{}}

Page 38: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

38

Throwing the user-defined exceptions

public uint NPeopleToRing{get{if (isDisposed)throw new

ObjectDisposedException("peopleToRing");if (!isOpen)throw new UnexpectedException("Attempted to access cold call file that is not

open");return nPeopleToRing;}}

Page 39: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

39

Throwing the user-defined exceptions

public void Dispose(){if (isDisposed)return;

isDisposed = true;isOpen = false;if (fs != null){fs.Close();fs = null;}}

Page 40: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

40

Defining the exception classes

class LandLineSpyFoundException : ApplicationException

{public LandLineSpyFoundException(string spyName): base("LandLine spy found, with name " +

spyName){}

public LandLineSpyFoundException(string spyName, Exception innerException): base("LandLine spy found with name " + spyName,

innerException){}}

Page 41: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

41

Defining the exception classes

class ColdCallFileFormatException : ApplicationException

{public ColdCallFileFormatException(string

message): base(message){}

public ColdCallFileFormatException(string message, Exception innerException): base(message, innerException){}}

Page 42: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

42

Defining the exception classes

class UnexpectedException : ApplicationException

{public UnexpectedException(string message): base(message){}

public UnexpectedException(string message, Exception innerException)

: base(message, innerException){}}

Page 43: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

43

Defining the exception classes

49George WashingtonZbigniew HarlequinJohn AdamsThomas Jefferson

Page 44: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

44

Defining the exception classes

MortimerColdCallMortimerColdCallPlease type in the name of the file

containing the names of the people to be cold-

called > people.txtGeorge WashingtonLandLine spy found, with name

Zbigniew HarlequinJohn AdamsThomas JeffersonAll callers processed correctly

Page 45: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

45

Defining the exception classes

MortimerColdCallMortimerColdCallPlease type in the name of the file

containing the names of the people to be cold-

called > people2.txtGeorge WashingtonLandLine spy found, with name Zbigniew

HarlequinJohn AdamsThomas JeffersonThe file people2.txt appears to have been

corruptedDetails of the problem are: Not enough

names

Page 46: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

46

Defining the exception classes

MortimerColdCallMortimerColdCallPlease type in the name of the file

containing the names of the people to be cold-

called > people3.txtThe file people3.txt does not exist

Page 47: ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

47

Summary

• This chapter took a close look at the rich mechanism This chapter took a close look at the rich mechanism C# has for dealing with error conditions through C# has for dealing with error conditions through exceptions. exceptions.

• You are not limited to the generic error codes that You are not limited to the generic error codes that could be output from your code, but you have the could be output from your code, but you have the ability to go in and uniquely handle the most granular ability to go in and uniquely handle the most granular of error conditions. of error conditions.

• Sometimes these error conditions are provided to you Sometimes these error conditions are provided to you through the .NET Framework itself, but at other through the .NET Framework itself, but at other times, you might want to go in and code your own times, you might want to go in and code your own error conditions as was shown in this chapter. error conditions as was shown in this chapter.

• In either case, you have a lot of ways of protecting the In either case, you have a lot of ways of protecting the workflow of your applications from unnecessary and workflow of your applications from unnecessary and dangerous faults.dangerous faults.