Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C-sharp language specification.2004.pdf
Скачиваний:
14
Добавлен:
23.08.2013
Размер:
2.55 Mб
Скачать

C# LANGUAGE SPECIFICATION

115.10 The try statement

2The try statement provides a mechanism for catching exceptions that occur during execution of a block.

3Furthermore, the try statement provides the ability to specify a block of code that is always executed when

4control leaves the try statement.

5try-statement:

6

try block catch-clauses

7

try block catch-clausesopt finally-clause

8

catch-clauses:

9

specific-catch-clauses

10

specific-catch-clausesopt general-catch-clause

11

specific-catch-clauses:

12

specific-catch-clause

13

specific-catch-clauses specific-catch-clause

14

specific-catch-clause:

15

catch ( class-type identifieropt ) block

16 general-catch-clause:

17catch block

18finally-clause:

19finally block

20There are three possible forms of try statements:

21A try block followed by one or more catch blocks.

22A try block followed by a finally block.

23A try block followed by one or more catch blocks followed by a finally block.

24When a catch clause specifies a class-type, the type shall be System.Exception or a type that derives

25from System.Exception.

26When a catch clause specifies both a class-type and an identifier, an exception variable of the given name

27and type is declared. The exception variable corresponds to a local variable with a scope that extends over

28the catch block. During execution of the catch block, the exception variable represents the exception

29currently being handled. For purposes of definite assignment checking, the exception variable is considered

30definitely assigned in its entire scope.

31Unless a catch clause includes an exception variable name, it is impossible to access the exception object

32in the catch block.

33The type named in a catch clause can be a type parameter only if that type parameter (§26.1.1) has

34System.Exception (or a subclass thereof) as its effective base class (§26.7).

35A catch clause that specifies neither an exception type nor an exception variable name is called a general

36catch clause. A try statement can only have one general catch clause, and if one is present it shall be the

37last catch clause.

38[Note: Some environments, especially those supporting multiple languages, might support exceptions that

39are not representable as an object derived from System.Exception, although such an exception could

40never be generated by C# code. In such an environment, a general catch clause might be used to catch such

41an exception. Thus, a general catch clause is semantically different from one that specifies the type

42System.Exception, in that the former might also catch exceptions from other languages. end note]

43In order to locate a handler for an exception, catch clauses are examined in lexical order. A compile-time

44error occurs if a catch clause specifies a type that is the same as, or is derived from, a type that was

45specified in an earlier catch clause for the same try. [Note: Without this restriction, it would be possible to

46write unreachable catch clauses. end note]

234

Chapter 15 Statements

1Within a catch block, a throw statement (§15.9.5) with no expression can be used to re-throw the

2exception that was caught by the catch block. Assignments to an exception variable do not alter the

3exception that is re-thrown.

4[Example: In the following code

5using System;

6class Test

7{

8

static void F() {

 

9

try {

 

10

G();

 

11

}

 

12

catch (Exception e) {

13

Console.WriteLine("Exception in F: " + e.Message);

14

e = new Exception("F");

15

throw;

// re-throw

16

}

 

17

}

 

18

static void G() {

 

19

throw new Exception("G");

20

}

 

21

static void Main() {

 

22

try {

 

23

F();

 

24

}

 

25

catch (Exception e) {

26

Console.WriteLine("Exception in Main: " + e.Message);

27

}

 

28}

29}

30the method F catches an exception, writes some diagnostic information to the console, alters the exception

31variable, and re-throws the exception. The exception that is re-thrown is the original exception, so the output

32produced is:

33Exception in F: G

34Exception in Main: G

35If the first catch block had thrown e instead of rethrowing the current exception, the output produced would

36be as follows:

37Exception in F: G

38Exception in Main: F

39end example]

40It is a compile-time error for a break, continue, or goto statement to transfer control out of a finally

41block. When a break, continue, or goto statement occurs in a finally block, the target of the statement

42shall be within the same finally block, or otherwise a compile-time error occurs.

43It is a compile-time error for a return statement to occur in a finally block.

44A try statement is executed as follows:

45Control is transferred to the try block.

46When and if control reaches the end point of the try block:

47o If the try statement has a finally block, the finally block is executed.

48o Control is transferred to the end point of the try statement.

49If an exception is propagated to the try statement during execution of the try block:

50o The catch clauses, if any, are examined in order of appearance to locate a suitable handler for the

51exception. The first catch clause that specifies the exception type or a base type of the exception

235

C# LANGUAGE SPECIFICATION

1type is considered a match. A general catch clause is considered a match for any exception type. If

2a matching catch clause is located:

3If the matching catch clause declares an exception variable, the exception object is assigned to

4

the exception variable.

5Control is transferred to the matching catch block.

6When and if control reaches the end point of the catch block:

7

o If the try statement has a finally block, the finally block is executed.

8o Control is transferred to the end point of the try statement.

9If an exception is propagated to the try statement during execution of the catch block:

10

o If the try statement has a finally block, the finally block is executed.

11o The exception is propagated to the next enclosing try statement.

12o If the try statement has no catch clauses or if no catch clause matches the exception:

13If the try statement has a finally block, the finally block is executed.

14The exception is propagated to the next enclosing try statement.

15The statements of a finally block are always executed when control leaves a try statement. This is true

16whether the control transfer occurs as a result of normal execution, as a result of executing a break,

17continue, goto, or return statement, or as a result of propagating an exception out of the try statement.

18If an exception is thrown during execution of a finally block, the exception is propagated to the next

19enclosing try statement. If another exception was in the process of being propagated, that exception is lost.

20The process of propagating an exception is discussed further in the description of the throw statement

21(§15.9.5).

22The try block of a try statement is reachable if the try statement is reachable.

23A catch block of a try statement is reachable if the try statement is reachable.

24The finally block of a try statement is reachable if the try statement is reachable.

25The end point of a try statement is reachable if both of the following are true:

26The end point of the try block is reachable or the end point of at least one catch block is reachable.

27If a finally block is present, the end point of the finally block is reachable.

2815.11 The checked and unchecked statements

29The checked and unchecked statements are used to control the overflow checking context for integral-

30type arithmetic operations and conversions.

31checked-statement:

32checked block

33unchecked-statement:

34unchecked block

35The checked statement causes all expressions in the block to be evaluated in a checked context, and the

36unchecked statement causes all expressions in the block to be evaluated in an unchecked context.

37The checked and unchecked statements are precisely equivalent to the checked and unchecked

38operators (§14.5.12), except that they operate on blocks instead of expressions.

236

Chapter 15 Statements

115.12 The lock statement

2The lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and then

3releases the lock.

4lock-statement:

5

lock ( expression ) embedded-statement

6The compile time type of the expression of a lock statement shall be a reference-type or a type parameter

7(§26.1.1). It is a compile-time error for the compile time type of the expression to denote a value-type. When

8the compile time type of expression is a type parameter (§26.1.1) and the run-time type of the expression is a

9value type, the value of the expression is boxed and the mutual exclusion lock is obtained on the boxed

10value. In this case the locking will have no effect since the boxed value could not have any other references

11to it.

12A lock statement of the form

13lock (x) …

14is precisely equivalent to:

15object obj = x;

16System.Threading.Monitor.Enter(obj);

17try {

18

19}

20finally {

21System.Threading.Monitor.Exit(obj);

22}

23[Example:

24class Cache

25{

26

public void Add(object x) {

27

lock (key) {

28

29

}

30

}

31

public void Remove(object x) {

32

lock (key) {

33

34

}

35

}

36private readonly object key = new object();

37}

38end example]

3915.13 The using statement

40The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

41using-statement:

42

using ( resource-acquisition ) embedded-statement

43

resource-acquisition:

44

local-variable-declaration

45

expression

46A resource is a class or struct that either has a suitable Dispose method or implements the

47System.IDisposable interface. The System.IDisposable interface includes a single parameterless

48method named Dispose. Code that is using a resource can call Dispose to indicate that the resource is no

49longer needed. If Dispose is not called, then automatic disposal eventually occurs as a consequence of

50garbage collection (assuming the destructor of the resource type calls Dispose or otherwise performs the

51equivalent actions).

237

C# LANGUAGE SPECIFICATION

1Local variables declared in a resource-acquisition are read-only, and shall include an initializer. A compile-

2time error occurs if the embedded statement attempts to modify these local variables (via assignment or the

3++ and -- operators) or pass them as ref or out parameters.

4A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is

5implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the

6resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

7A using statement of the form

8using (expression) embedded-statement

9is equivalent to a using statement of the form:

10using (ResourceType resource = expression) embedded-statement

11where ResourceType is the type of the expression and the resource variable is not visible to or

12accessible from any source code of the program.

13A using statement of the form

14using (ResourceType resource = expression) embedded-statement

15corresponds to the expansion:

16{

17

ResourceType resource = expression;

18

try {

19

embedded-statement

20

}

21

finally {

22

… // Dispose of resource

23}

24}

25The resource variable is read-only in the embedded statement.

26The precise form of the finally block is determined as follows:

27First determine whether the resource type R has an appropriate Dispose method:

28o Perform member lookup on the type R with identifier Dispose and no type arguments. If the

29member lookup does not produce a match or produces an ambiguity or produces a match that is not

30a method group, check for the System.IDisposable interface as described below. It is

31recommended that a warning be issued if member lookup produces anything except a method group

32or no match.

33o Perform overload resolution using the resulting method group and an empty argument list. If

34overload resolution results in no applicable methods or results in an ambiguity or results in a single

35best method but that method is either static or not public or has a return type other than void, check

36for the System.IDisposable interface as described below. It is recommended that a warning be

37issued if overload resolution produces anything except an unambiguous public instance method with

38void return type or no applicable methods.

39o If ResourceType is a value type or a type parameter with the value type constraint (§26.7), the

40finally clause is expanded to:

41finally {

42resource.Dispose();

43}

44o Otherwise, the finally clause is expanded to:

45finally {

46if (resource != null) resource.Dispose();

47}

48Otherwise, check for the System.IDisposable interface:

238

Соседние файлы в предмете Электротехника