X hits on this document





195 / 396


The try statement provides a mechanism for catching exceptions that occur during execution of a block. Furthermore, the try statement provides the ability to specify a block of code that is always executed when control leaves the try statement.

try-statement: try   block   catch-clauses try   block   finally-clause try   block   catch-clauses   finally-clause

catch-clauses: specific-catch-clauses   general-catch-clauseopt specific-catch-clausesopt   general-catch-clause

specific-catch-clauses: specific-catch-clause specific-catch-clauses   specific-catch-clause

specific-catch-clause: catch   (   class-type   identifieropt   )   block

general-catch-clause: catch   block

finally-clause: finally   block

There are three possible forms of try statements:

A try block followed by one or more catch blocks.

A try block followed by a finally block.

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

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

When a catch clause specifies both a class-type and an identifier, an exception variable of the given name and type is declared. The exception variable corresponds to a local variable with a scope that extends over the catch block. During execution of the catch block, the exception variable represents the exception currently being handled. For purposes of definite assignment checking, the exception variable is considered definitely assigned in its entire scope.

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

A catch clause that specifies neither an exception type nor an exception variable name is called a general catch clause. A try statement can only have one general catch clause, and if one is present it must be the last catch clause.

Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code. A general catch clause may be used to catch such exceptions. Thus, a general catch clause is semantically different from one that specifies the type System.Exception, in that the former may also catch exceptions from other languages.

In order to locate a handler for an exception, catch clauses are examined in lexical order. A compile-time error occurs if a catch clause specifies a type that is the same as, or is derived from, a type that was specified in an earlier catch clause for the same try. Without this restriction, it would be possible to write unreachable catch clauses.

182Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views1261
Page views1261
Page last viewedFri Jan 20 10:03:28 UTC 2017