楼主: bnso

Introduction to C# Programming

[复制链接]
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
31#
 楼主| 发表于 2006-8-13 21:11 | 只看该作者
50 Module 4: Statements and Exceptions
If a general catch block is present, it must be the last catch block in the
program, as follows:
try {
}
catch { ... } // Error
catch (OutOfMemoryException caught) { ... }
You will generate an error if you catch the same class twice, as in the following
example:
catch (OutOfMemoryException caught) { ... }
catch (OutOfMemoryException caught) { ... } // Error
You will also generate an error if you try to catch a class that is derived from a
class caught in an earlier catch block, as follows:
catch (Exception caught) { ... }
catch (OutOfMemoryException caught) { ... }
This code results in an error because the OutOfMemoryException class is
derived from the SystemException class, which is in turn derived from the
Exception class.
Module 4: Statements and Exceptions 51
u Raising Exceptions
n The throw Statement
n The finally Clause
n Checking for Arithmetic Overflow
n Guidelines for Handling Exceptions
C# provides the throw statement and the finally clause so that programmers
can raise exceptions if required and handle them as appropriate. In this section,
you will learn how to raise your own exceptions. You will also learn how to
enable checking for arithmetic overflow as appropriate for your programs.
52 Module 4: Statements and Exceptions
The throw Statement
n Throw an Appropriate Exception
n Give the Exception a Meaningful Message
tthhrrooww eexxpprreessssiioonn ;;
if (minute < 1 || minute > 59) {
throw new InvalidTimeException(minute +
"is not a valid minute";
// !! Not reached !!
}
if (minute < 1 || minute > 59) {
throw new InvalidTimeException(minute +
"is not a valid minute";
// !! Not reached !!
}
The try and catch blocks are used to trap errors that are raised by a C# program.
You have seen that instead of signaling an error by returning a special value, or
assigning it to a global error variable, C# causes execution to be transferred to
the appropriate catch clause.
System-Defined Exceptions
When it needs to raise an exception, the runtime executes a throw statement
and raises a system-defined exception. This immediately suspends the normal
sequential execution of the program and transfers control to the first catch
block that can handle the exception based on its class.
Module 4: Statements and Exceptions 53
Raising Your Own Exceptions
You can use the throw statement to raise your own exceptions, as shown in the
following example:
if (minute < 1 || minute >= 60) {
string fault = minute + "is not a valid minute";
throw new InvalidTimeException(fault);
// !!Not reached!!
}
In this example, the throw statement is used to raise a user-defined exception,
InvalidTimeException, if the time being parsed does not constitute a valid time.
Exceptions typically expect a meaningful message string as a parameter when
they are created. This message can be displayed or logged when the exception
is caught. It is also good practice to throw an appropriate class of exception.
C++ programmers will be accustomed to creating and throwing an
exception object with a single statement, as shown in the following code:
throw out_of_range("type: index out of bounds";
The syntax in C# is very similar but requires the new keyword, as follows:
throw new FileNotFoundException("...";
Throwing Objects
You can only throw an object if the type of that object is directly or indirectly
derived from System.Exception. This is different from C++, in which objects
of any type can be thrown, such as in the following code:
throw 42; // Allowed in C++, but not in C#
You can use a throw statement in a catch block to rethrow the current
exception object, as in the following example:
catch (Exception caught) {
...
throw caught;
}
You can also throw a new exception object of a different type:
catch (FileIOException caught) {
...
throw new FileNotFoundException(filename);
}
Caution

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
32#
 楼主| 发表于 2006-8-13 21:11 | 只看该作者
54 Module 4: Statements and Exceptions
In the preceding example, notice that the FileIOException object, and any
information it contains, is lost when the exception is converted into a
FileNotFoundException object. A better idea is to wrap the exception, adding
new information but retaining existing information as shown in the following
code:
catch (FileIOException caught) {
...
throw new FileNotFoundException(filename, caught);
}
This ability to map an exception object is particularly useful at the boundaries
of a layered system architecture.
A throw statement with no expression can be used, but only in a catch block. It
rethrows the exception that is currently being handled. This action is called a
rethrow in C++ as well. Therefore, the following two lines of code produce
identical results:
catch (OutOfMemoryException caught) { throw caught; }
...
catch (OutOfMemoryException) { throw ; }
You can use a rethrow in a general catch block to implement partial recovery:
StreamReader reader = new StreamReader(filename);
try {
...
}
catch {
reader.Close( );
throw;
}
Module 4: Statements and Exceptions 55
The finally Clause
n All of the Statements in a finally Block Are Always
Executed
CriticalSection.Enter(x);
try {
...
}
finally {
CriticalSection.Exit(x);
}
CriticalSection.Enter(x);
try {
...
}
finally {
CriticalSection.Exit(x);
}
AAnnyy c caattcchh b blolocckkss a arree o oppttioionnaall
C# provides the finally clause to enclose a set of statements that need to be
executed regardless of the course of control flow. Therefore, if control leaves a
try block as a result of normal execution because the control flow reaches the
end of the try block, the statements of the finally block are executed. Also, if
control leaves a try block as a result of a throw statement or a jump statement
such as break , continue, or goto, the statements of the finally block are
executed.
The finally block is useful in two situations: to avoid duplication of statements
and to release resources after an exception has been thrown.
Avoiding Duplication of Statements
If the statements at the end of a try block are duplicated in a general catch
block, the duplication can be avoided by moving the statements into a finally
block. Consider the following example:
try {
...
statement
}
catch {
...
statement
}

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
33#
 楼主| 发表于 2006-8-13 21:12 | 只看该作者
56 Module 4: Statements and Exceptions
You can simplify the preceding code by rewriting it as follows:
try {
...
}
catch {
...
}
finally {
statement
}
Releasing Resources
If a statement in a try block acquires a resource such as a file handle, the
corresponding statement that releases the resource can be placed in a finally
block. This ensures that the resource will be released even if an exception arises
from the try block. The following code provides an example:
StreamReader reader = null;
try {
File source = new File(filename);
reader = source.OpenText( );
...
}
finally {
if (reader != null) {
reader.Close( );
}
}
It is an error for a break, continue , or goto statement to transfer control out of
a finally block. They can be used only if the target of the jump is within the
same finally block. However, it is always an error for a return statement to
occur in a finally block, even if the return statement is the last statement in the
block.
Module 4: Statements and Exceptions 57
If an exception is thrown during the execution of a finally block, it is
propagated to the next enclosing try block, as shown:
try {
try {
...
}
catch {
// ExampleException is not caught here
}
finally {
throw new ExampleException("who will catch me?";
}
}
catch {
// ExampleException is caught here
}
If an exception is thrown during the execution of a finally block, and another
exception was in the process of being propagated, then the original exception is
lost, as shown:
try {
throw ExampleException("Will be lost";
}
finally {
throw ExampleException("Might be found and caught";
}
58 Module 4: Statements and Exceptions
Checking for Arithmetic Overflow
n By Default, Arithmetic Overflow Is Not Checked
l 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
OOvveerrfflloowwEExxcceeppttiioonn
Exception object is thrown.
WriteLine is not executed.
MaxValue + 1 is negative?
By default, a C# program will not check arithmetic for overflow. The following
code provides an example:
// example.cs
class Example
{
static void Main( )
{
int number = int.MaxValue( );
Console.WriteLine(++number);
}
}
In the preceding code, number is initialized to the maximum value for an int.
The expression ++number increments number to –2147483648, the largest
negative int value, which is then written to the console. No error message is
generated.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
34#
 楼主| 发表于 2006-8-13 21:12 | 只看该作者
Module 4: Statements and Exceptions 59
Controlling Arithmetic Overflow Checking
When compiling a C# program, you can globally turn on arithmetic overflow
checking by using the /checked+ command line option, as follows:
c:\ csc /checked+ example.cs
The resulting executable program will cause an exception of class
System.OverflowException.
Similarly, you can turn off global arithmetic overflow checking by using the
/checked- command line option, as follows:
c:\ csc /checked- example.cs
The resulting executable program will silently wrap the int value back to zero
and will not cause an exception of class System.OverflowException.
Creating Checked and Unchecked Statements
You can use the checked and unchecked keywords to create statements that are
explicitly checked or unchecked statements:
checked { statement-list }
unchecked { statement-list }
Regardless of the compile-time /checked setting, the statements inside a
checked statement list are always checked for arithmetic overflow. Similarly,
regardless of the compile-time /checked setting, the statements inside an
unchecked statement list are never checked for arithmetic overflow.
Creating Checked and Unchecked Expressions
You can also use the checked and unchecked keywords to create checked and
unchecked expressions:
checked ( expression )
unchecked ( expression )
A checked expression is checked for arithmetic overflow; an unchecked
expression is not. For example, the following code will generate a
System.OverflowException.
// example.cs
class Example
{
static void Main( )
{
int number = int.MaxValue( );
Console.WriteLine(checked(++number));
}
}
60 Module 4: Statements and Exceptions
Guidelines for Handling Exceptions
n Throwing
l Avoid exceptions for normal or expected cases
l Never create and throw objects of class Exception
l Include a description string in an Exception object
l Throw objects of the most specific class possible
n Catching
l Arrange catch blocks from specific to general
l Do not let exceptions drop off Main
Use the following guidelines for handling exceptions:
n Avoid exceptions for normal or expected cases.
In general, do not throw exceptions in normal or common cases. For
example, it is relatively common to fail to open a named file, so the
File.Open method returns null to signify that the file could not be found
rather than throwing an exception.
n Never create or throw objects of class Exception.
Create exception classes that are derived directly or indirectly from
SystemException (and never from the root Exception class). The following
code provides an example:
class SyntaxException : SystemException
{
...
}
n Include a description string in an Exception object.
Always include a useful description string in an exception object, as shown:
string description =
String.Format("{0}({1}): newline in string constant",
filename, linenumber);
throw new SyntaxException(description);
n Throw objects of the most specific class possible.
Throw the most specific exception possible when the user might be able to
use this specific information. For example, throw a
FileNotFoundException rather than a more general FileIOException.
Module 4: Statements and Exceptions 61
n Arrange catch blocks from specific to general.
Arrange your catch blocks from the most specific exception to the most
general exception, as shown:
catch (Exception caught) { ... } // Do not do this
catch (SyntaxException caught) { ... }
catch (SyntaxException caught) { ... } // Do this
catch (Exception caught) { ... }
n Do not let exceptions drop off Main.
Put a general catch clause in Main to ensure that exceptions never drop off
the end of the program.
static void Main( )
{
try {
...
}
catch (Exception caught) {
...
}
}

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
35#
 楼主| 发表于 2006-8-13 21:12 | 只看该作者
62 Module 4: Statements and Exceptions
Lab 4.2: Using Exceptions
Objectives
After completing this lab, you will be able to:
n Throw and catch exceptions.
n Display error messages.
Prerequisites
Before working on this lab, you should be familiar with the following:
n Creating variables in C#
n Using common operators in C#
n Creating enum types in C#
Esti mated time to complete this lab: 30 minutes
Module 4: Statements and Exceptions 63
Exercise 1
Validating the Day Number
In this exercise, you will add functionality to the program that you created in
Exercise 1. The program will examine the initial day number that is entered by
the user. If it is less than 1 or greater than 365, the program will throw an
InvalidArgument exception (“Day out of range”). The program will trap this
exception in a catch clause and display a diagnostic message on the console.
? To validate the day number
1. Open the project WhatDay2.csproj in the install folder\
Labs\Lab04\Starter\WhatDay2 folder.
2. Enclose the entire contents of WhatDay.Main in a try block.
3. After the try block, add a catch clause that catches exceptions of type
System.Exception and name them caught. In the catch block, add a
WriteLine statement to write the exception caught to the console.
4. Add an if statement after the declaration of the dayNum variable. The if
statement will throw a new exception object of type
System.ArgumentOutOfRangeException if dayNum is less than 1 or
greater than 365. Use the string literal “Day out of range” to create the
exception object.
64 Module 4: Statements and Exceptions
5. The completed program should be as follows:
using System;
enum MonthName { ... }
class WhatDay
{
static void Main( )
{
try {
Console.Write("Please enter a day number
êbetween 1 and 365: ";
string line = Console.ReadLine( );
int dayNum = int.Parse(line);
if (dayNum < 1 || dayNum > 365) {
throw new ArgumentOutOfRangeException("Day
êout of range";
}
int monthNum = 0;
foreach (int daysInMonth in DaysInMonths) {
if (dayNum <= daysInMonth) {
break;
} else {
dayNum -= daysInMonth;
monthNum++;
}
}
MonthName temp = (MonthName)monthNum;
string monthName = temp.Format( );
Console.WriteLine("{0} {1}", dayNum,
êmonthName);
}
catch (Exception caught) {
Console.WriteLine(caught);
}
}
...
}
6. Save your work.
7. Compile the WhatDay2.cs program and correct any errors. Run the program.
Use the table of data provided in Lab4.1 (Exercise 1) to verify that the
program is still working correctly.
8. Run the program, entering day numbers less than 1 and greater than 365.
Verify that invalid input is safely trapped and that the exception object is
thrown, caught, and displayed.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
36#
 楼主| 发表于 2006-8-13 21:13 | 只看该作者
Module 4: Statements and Exceptions 65
Exercise 2
Handling Leap Years
In this exercise, you will add functionality to the program that you worked on in
Exercise 1. After you complete this exercise, the program will prompt the user
for a year in addition to a day number. The program will detect whether the
specified year is a leap year. It will validate whether the day number is between
1 and 366 if the year is a leap year, or whether it is between 1 and 365 if the
year is not a leap year. Finally, it will use a new foreach statement to correctly
calculate the month and day pair for leap years.
? To enter the year from the console
1. Open the WhatDay3.csproj project in the install folder\
Labs\Lab04\Starter\WhatDay3 folder.
2. Add to the beginning of WhatDay.Main a System.Console.Write
statement that writes a prompt to the console asking the user to enter a year.
3. Change the declaration and initialization of the string line to an assignment.
Change string line = Console.ReadLine( ); to
line = Console.ReadLine( );.
4. Add a statement to Main that declares a string variable called line and
initializes it with a line read from the console by the
System.Console.ReadLine method.
5. Add a statement to Main that declares an int variable called yearNum and
initializes it with the integer returned by the int.Parse method.
66 Module 4: Statements and Exceptions
6. The completed program should be as follows:
using System;
enum MonthName { ... }
class WhatDay
{
static void Main( )
{
try {
Console.Write("Please enter the year: ";
string line = Console.ReadLine( );
int yearNum = int.Parse(line);
Console.Write("Please enter a day number
êbetween 1 and 365: ";
line = Console.ReadLine( );
int dayNum = int.Parse(line);
// As before....
}
catch (Exception caught) {
Console.WriteLine(caught);
}
}
...
}
7. Save your work.
8. Compile the WhatDay3.cs program and correct any errors.
? To determine whether the year is a leap year
1. Add a statement immediately after the declaration of yearNum that declares
a bool variable called isLeapYear. Initialize this variable with a Boolean
expression that determines whether yearNum is a leap year. A year is a leap
year if the following two statements are both true:
· It is divisible by 4.
· It is either not divisible by 100, or it is divisible by 400.
2. Add an if statement immediately after the declaration of isLeapYear. In the
if statement, write the string “ IS a leap year” or “ is NOT a leap year” to the
console, depending on the value of isLeapyear. You will use this if
statement to verify that the Boolean leap year determination is correct.
Module 4: Statements and Exceptions 67
3. The completed program should be as follows:
using System;
enum MonthName { ... }
class WhatDay
{
static void Main( )
{
try
{
Console.Write("Please enter the year: ";
string line = Console.ReadLine( );
int yearNum = int.Parse(line);
bool isLeapYear = (yearNum % 4 == 0)
&& (yearNum % 100 != 0
|| yearNum % 400 == 0);
if (isLeapYear)
{
Console.WriteLine(" IS a leap year";
} else
{
Console.WriteLine(" is NOT a leap year";
}
Console.Write("Please enter a day number
êbetween 1 and 365: ";
line = Console.ReadLine( );
int dayNum = int.Parse(line);
// As before...
}
catch (Exception caught)
{
Console.WriteLine(caught);
}
}
...
}
4. Save your work.
5. Compile the WhatDay3.cs program and correct any errors. Use the
following table to verify that the Boolean leap year determination is correct.
A leap year Not a leap year
1996 1999
2000 1900
2004 2001
6. Comment out the if statement that you added in step 2.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
37#
 楼主| 发表于 2006-8-13 21:13 | 只看该作者
68 Module 4: Statements and Exceptions
? To validate the day number against 365 or 366
1. Immediately after the declaration of isLeapYear, add a declaration of an int
variable called maxDayNum. Initialize maxDayNum with either 366 or 365,
depending on whether isLeapYear is true or false, respectively.
2. Change the WriteLine statement that prompts the user for the day number.
It should display the range 1 to 366 if a leap year was entered and 1 to 365 if
a non–leap year was entered.
3. Compile the WhatDay3.cs program and correct any errors. Run the program
and verify that you have implemented the previous step correctly.
4. Change the if statement that validates the value of dayNum to use the
variable maxDayNum instead of the literal 365.
5. The completed program should be as follows:
using System;
enum MonthName { ... }
class WhatDay
{
static void Main( )
{
try
{
Console.Write("Please enter the year: ";
string line = Console.ReadLine( );
int yearNum = int.Parse(line);
bool isLeapYear = (yearNum % 4 == 0)
&& (yearNum % 100 != 0
|| yearNum % 400 == 0);
int maxDayNum = isLeapYear ? 366 : 365;
Console.Write("Please enter a day number
êbetween 1 and {0}: ", maxDayNum);
line = Console.ReadLine( );
int dayNum = int.Parse(line);
if (dayNum < 1 || dayNum > maxDayNum) {
throw new ArgumentOutOfRangeException("Day
êout of range";
}
// As before....
}
catch (Exception caught)
{
Console.WriteLine(caught);
}
}
...
}
Module 4: Statements and Exceptions 69
6. Save your work.
7. Compile the WhatDay3.cs program and correct any errors. Run the program
and verify that you have implemented the previous step correctly.
? To correctly calculate the month and day pair for leap years
1. After the if statement that validates the day number and the declaration of
the monthNum integer, add an if-else statement. The Boolean expression
used in this if-else statement will be the variable isLeapYear.
2. Move the foreach statement so it becomes the embedded statement in the ifelse
statement in both the true and the false cases. After this step, your code
should be as follows:
if (isLeapYear)
{
foreach (int daysInMonth in DaysInMonths) {
...
}
} else
{
foreach (int daysInMonth in DaysInMonths) {
...
}
}
3. Save your work.
4. Compile the WhatDay3.cs program and correct any errors. Run the program
and verify that day numbers in non–leap years are still handled correctly.
5. The next step will use the DaysInLeapMonths collection that has been
provided. This is a collection of int values like DaysInMonths, except that
the second value in the collection (the number of days in February) is 29
rather than 28.
6. Use DaysInLeapMonths instead of DaysInMonth in the true part of the
if-else statement.
70 Module 4: Statements and Exceptions
7. The completed program should be as follows:
using System;
enum MonthName { ... }
class WhatDay
{
static void Main( )
{
try {
Console.Write("Please enter the year: ";
string line = Console.ReadLine( );
int yearNum = int.Parse(line);
bool (isLeapYear = yearNum % 4 == 0)
&& (yearNum % 100 != 0
|| yearNum % 400 == 0);
int maxDayNum = isLeapYear ? 366 : 365;
Console.Write("Please enter a day number
êbetween 1 and {0}: ", maxDayNum);
line = Console.ReadLine( );
int dayNum = int.Parse(line);
if (dayNum < 1 || dayNum > maxDayNum) {
throw new ArgumentOutOfRangeException("Day
êout of range";
}
int monthNum = 0;
if (isLeapYear) {
foreach (int daysInMonth in
êDaysInLeapMonths) {
if (dayNum <= daysInMonth) {
break;
} else {
dayNum -= daysInMonth;
monthNum++;
}
}
} else {
foreach (int daysInMonth in DaysInMonths) {
if (dayNum <= daysInMonth) {
break;
} else {
dayNum -= daysInMonth;
monthNum++;
}
}
}
(Code continued on following page.)

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
38#
 楼主| 发表于 2006-8-13 21:13 | 只看该作者
Module 4: Statements and Exceptions 71
MonthName temp = (MonthName)monthNum;
string monthName = temp.Format( );
Console.WriteLine("{0} {1}", dayNum,
êmonthName);
}
catch (Exception caught) {
Console.WriteLine(caught);
}
}
...
}
8. Save your work.
9. Compile the WhatDay3.cs program and correct any errors. Run the program,
using the data in the following table to verify that the program is working
correctly.
Year Day Number Month-Day Pair
1999 32 February 1
2000 32 February 1
1999 60 March 1
2000 60 February 29
1999 91 April 1
2000 91 March 31
1999 186 July 5
2000 186 July 4
1999 304 October 31
2000 304 October 30
1999 309 November 5
2000 309 November 4
1999 327 November 23
2000 327 November 22
1999 359 December 25
2000 359 December 24
72 Module 4: Statements and Exceptions
Review
n Introduction to Statements
n Using Selection Statements
n Using Iteration Statements
n Using Jump Statements
n Handling Basic Exceptions
n Raising Exceptions
s
1. Write an if statement that tests whether an int variable called hour is greater
than or equal to zero and less than 24. If it is not, reset hour to zero.
2. Write a do-while statement, the body of which reads an integer from the
console and stores it in an int called hour. Write the loop so that the loop
will exit only when hour has a value between 1 and 23 (inclusive).
Module 4: Statements and Exceptions 73
3. Write a for statement that meets all of the conditions of the preceding
question and only allows five attempts to input a valid value for hour. Do
not use break or continue statements.
4. Rewrite the code that you wrote for question 3, but this time use a break
statement.
5. Write a statement that throws an exception of type
ArgumentOutOfRangeException if the variable percent is less than zero
or greater than 100.
74 Module 4: Statements and Exceptions
6. The following code is meant to read from a file by using a StreamReader
resource. It carefully closes the StreamReader resource by calling its Close
method. Explain why this code is not exception safe and loses resources
when exceptions are thrown. Use a try-finally block to fix the problem.
File source = new File("code.cs";
StreamReader reader = source.OpenText( );
//... Use reader
reader.Close( );

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
39#
 楼主| 发表于 2006-8-13 21:14 | 只看该作者
Contents
Overview 1
Using Methods 2
Using Parameters 16
Using Overloaded Methods 30
Lab 5: Creating and Using Methods 38
Review 50
Module 5: Methods and
Parameters
This course is based on the prerelease Beta 1 version of Microsoft? Visual Studio .NET.
Content in the final release of the course may be different from the content included in
this prerelease version. All labs in the course are to be completed with the Beta 1
version of Visual Studio .NET.
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
ó 2001 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BizTalk, IntelliSense, JScript, Microsoft Press, MSDN, PowerPoint, Visual
Basic, Visual C++, Visual C#, Visual Studio, Windows, Windows NT, and Windows Media are
either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other
countries.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 5: Methods and Parameters 1
Overview
n Using Methods
n Using Parameters
n Using Overloaded Methods
In designing most applications, you divide the application into functional units.
This is a central principle of application design because small sections of code
are easier to understand, design, develop, and debug. Dividing the application
into functional units also allows you to reuse functional components throughout
the application.
In C#, you structure your application into classes that contain named blocks of
code; these are called methods. A method is a member of a class that performs
an action or computes a value.
After completing this module, you will be able to:
n Create static methods that accept parameters and return values.
n Pass parameters to methods in different ways.
n Declare and use overloaded methods.
2 Module 5: Methods and Parameters
u Using Methods
n Defining Methods
n Calling Methods
n Using the return Statement
n Using Local Variables
n Returning Values
In this section, you will learn how to use methods in C#. Methods are important
mechanisms for struc turing program code. You will learn how to create
methods and how to call them from within a single class and from one class to
another.
You will learn how to use local variables, as well as how to allocate and
destroy them.
You will also learn how to return a value from a method, and how to use
parameters to transfer data into and out of a method.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
40#
 楼主| 发表于 2006-8-13 21:14 | 只看该作者
Module 5: Methods and Parameters 3
Defining Methods
n Main Is a Method
l Use the same syntax for defining your own methods
using System;
class ExampleClass
{
static void ExampleMethod( )
{
Console.WriteLine("Example method";
}
static void Main( )
{
// ...
}
}
using System;
class ExampleClass
{
static void ExampleMethod( )
{
Console.WriteLine("Example method";
}
static void Main( )
{
// ...
}
}
A method is group of C# statements that have been brought together and given
a name. Most modern programming languages have a similar concept; you can
think of a method as being like a function, a subroutine, a procedure or a
subprogram.
Examples of Methods
The code on the slide contains three methods:
n The Main method
n The WriteLine method
n The ExampleMethod method
The Main method is the entry point of the application. The WriteLine method
is part of the Microsoft? .NET Framework. It can be called from within your
program. The WriteLine method is a static method of the class
System.Console. The ExampleMethod method belongs to ExampleClass.
This method calls the WriteLine method.
In C#, all methods belong to a class. This is unlike programming languages
such as C, C++, and Microsoft Visual Basic?, which allow global subroutines
and functions.
4 Module 5: Methods and Parameters
Creating Methods
When creating a method, you must specify the following:
n Name
You cannot give a method the same name as a variable, a constant, or any
other non-method item declared in the class. The method name can be any
allowable C# identifier, and it is case sensitive.
n Parameter list
The method name is followed by a parameter list for the method. This is
enclosed between parentheses. The parentheses must be supplied even if
there are no parameters, as is shown in the examples on the slide.
n Body of the method
Following the parentheses is the body of the method. You must enclose the
method body within braces ({ and }), even if there is only one statement.
Syntax for Defining Methods
To create a method, use the following syntax:
static void MethodName ( )
{
method body
}
The following example shows how to create a method named ExampleMethod
in the ExampleClass class:
using System;
class ExampleClass
{
static void ExampleMethod( )
{
Console.WriteLine("Example method";
}
static void Main( )
{
Console.WriteLine("Main method";
}
}
Method names in C# are case-sensitive. Therefore, you can declare and
use methods with names that differ only in case. For example, you can declare
methods called print and PRINT in the same class. However, the Common
Language Runtime requires that method names within a class differ in ways
other than case alone, to ensure compatibility with languages in which method
names are case-insensitive. This is important if you want your application to
interact with applications written in languages other than C#.
Note

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 未成年人举报专区 
京ICP备16024965号-8  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表