Você está na página 1de 9

Try...Catch...

Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

Try...Catch...Finally Statement (Visual Basic)


Visual Studio 2013 . out o! / rated this help!ul Provides a way to handle some or all possible errors that may occur in a given bloc o! code" while still running code.

Try [ tryStatements ] [ Exit Try ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] [ Exit Try ] ] [ Catch ... ] [ Finally [ finallyStatements ] ] End Try

Parts
Term tryStatements Catch #e!inition $ptional. Statement(s) where an error can occur. Can be a compound statement. $ptional. %ultiple Catch bloc s permitted. &! an e'ception occurs when processing the Try bloc " each Catch statement is e'amined in te'tual order to determine whether it handles the e'ception" with exception representing the e'ception that has been thrown. $ptional. (ny variable name. The initial value o! exception is the value o! the thrown error. )sed with Catch to speci!y the error caught. &! omitted" the Catch statement catches any e'ception. $ptional. Speci!ies the type o! class !ilter. &! the value o! exception is o! the type speci!ied by type or o! a derived type" the identi!ier becomes bound to the e'ception ob*ect. $ptional. ( Catch statement with a When clause catches e'ceptions only when expression evaluates to True. ( When clause is applied only a!ter chec ing the type o! the e'ception" and expression may re!er to the identi!ier representing the e'ception. $ptional. %ust be implicitly convertible to Boolean. (ny e'pression that describes a generic !ilter. Typically used to !ilter by error number. )sed with When eyword to speci!y circumstances under which the error is caught. $ptional. Statement(s) to handle errors that occur in the associated Try bloc . Can be a compound statement. $ptional. +eyword that brea s out o! the Try...Catch...Finally structure. ,'ecution resumes with the code immediately !ollowing the End Try statement. The Finally statement will still be e'ecuted. -ot allowed in Finally bloc s.

exception

type

When

expression

catchStatements

Exit Try

% of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

Finally

$ptional. ( Finally bloc is always e'ecuted when e'ecution leaves any part o! the Try...Catch statement. $ptional. Statement(s) that are e'ecuted a!ter all other error processing has occurred. Terminates the Try...Catch...Finally structure.

finallyStatements End Try

0emar s
&! you e'pect that a particular e'ception might occur during a particular section o! code" put the code in a Try bloc and use a Catch bloc to retain control and handle the e'ception i! it occurs. ( TryCatch statement consists o! a Try bloc !ollowed by one or more Catch clauses" which speci!y handlers !or various e'ceptions. 1hen an e'ception is thrown in a Try bloc " Visual Basic loo s !or the Catch statement that handles the e'ception. &! a matching Catch statement is not !ound" Visual Basic e'amines the method that called the current method" and so on up the call stac . &! no Catch bloc is !ound" Visual Basic displays an unhandled e'ception message to the user and stops e'ecution o! the program. 2ou can use more than one Catch statement in a TryCatch statement. &! you do this" the order o! the Catch clauses is signi!icant because they are e'amined in order. Catch the more speci!ic e'ceptions be!ore the less speci!ic ones. The !ollowing Catch statement conditions are the least speci!ic" and will catch all e'ceptions that derive !rom the ,'ception class. 2ou should ordinarily use one o! these variations as the last Catch bloc in the Try...Catch...Finally structure" a!ter catching all the speci!ic e'ceptions you e'pect. Control !low can never reach a Catch bloc that !ollows either o! these variations.

The type is Exception" !or e'ample3 Catch ex As Exception The statement has no exception variable" !or e'ample3 Catch

1hen a TryCatchFinally statement is nested in another Try bloc " Visual Basic !irst e'amines each Catch statement in the innermost Try bloc . &! no matching Catch statement is !ound" the search proceeds to the Catch statements o! the outer TryCatchFinally bloc . 4ocal variables !rom a Try bloc are not available in a Catch bloc because they are separate bloc s. &! you want to use a variable in more than one bloc " declare the variable outside the Try...Catch...Finally structure. Tip The TryCatchFinally statement is available as an &ntelliSense code snippet. &n the Code Snippets %anager" e'pand Code atterns ! "#$ For Each$ Try Catch$ roperty$ etc" and then Error %andlin& 'Exceptions(. For more in!ormation" see Code Snippets.

Finally Bloc
&! you have one or more statements that must run be!ore you e'it the Try structure" use a Finally bloc . Control passes to the Finally bloc *ust be!ore it passes out o! the TryCatch structure. This is true even i! an e'ception occurs anywhere inside the Try structure. ( Finally bloc is use!ul !or running any code that must e'ecute even i! there is an e'ception. Control is passed to the Finally bloc regardless o! how the Try...Catch bloc e'its. The code in a Finally bloc runs even i! your code encounters a )eturn statement in a Try or Catch bloc . Control does not

' of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

pass !rom a Try or Catch bloc to the corresponding Finally bloc in the !ollowing cases3

(n ,nd Statement is encountered in the Try or Catch bloc . ( Stac $ver!low,'ception is thrown in the Try or Catch bloc .

&t is not valid to e'plicitly trans!er e'ecution into a Finally bloc . Trans!erring e'ecution out o! a Finally bloc is not valid" e'cept through an e'ception. &! a Try statement does not contain at least one Catch bloc " it must contain a Finally bloc . Tip &! you do not have to catch speci!ic e'ceptions" the *sin& statement behaves li e a TryFinally bloc " and guarantees disposal o! the resources" regardless o! how you e'it the bloc . This is true even with an unhandled e'ception. For more in!ormation" see )sing Statement (Visual Basic).

,'ception (rgument
The Catch bloc exception argument is an instance o! the ,'ception class or a class that derives !rom the Exception class. The Exception class instance corresponds to the error that occurred in the Try bloc . The properties o! the Exception ob*ect help to identi!y the cause and location o! an e'ception. For e'ample" the Stac Trace property lists the called methods that led to the e'ception" helping you !ind where the error occurred in the code. %essage returns a message that describes the e'ception. 5elp4in returns a lin to an associated 5elp !ile. &nner,'ception returns the Exception ob*ect that caused the current e'ception" or it returns +othin& i! there is no original Exception.

Considerations 1hen )sing a Try6Catch Statement


)se a TryCatch statement only to signal the occurrence o! unusual or unanticipated program events. 0easons !or this include the !ollowing3

Catching e'ceptions at runtime creates additional overhead" and is li ely to be slower than pre7chec ing to avoid e'ceptions. &! a Catch bloc is not handled correctly" the e'ception might not be reported correctly to users. ,'ception handling ma es a program more comple'.

2ou do not always need a TryCatch statement to chec !or a condition that is li ely to occur. The !ollowing e'ample chec s whether a !ile e'ists be!ore trying to open it. This reduces the need !or catching an e'ception thrown by the $penTe't method. VB Private Su TextFileExample!"y#al filePath As Strin$%

& #erify that the file exists. 'f System.'(.File.Exists!filePath% ) False Then Console.Write!*File +ot Found, * - filePath% Else & (pen the text file and display its contents. .im sr As System.'(.Stream/eader ) System.'(.File.(penText!filePath% Console.Write!sr./eadToEnd%

+ of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

sr.Close!% End 'f End Su

,nsure that code in Catch bloc s can properly report e'ceptions to users" whether through thread7sa!e logging or appropriate messages. $therwise" e'ceptions might remain un nown.

(sync %ethods
&! you mar a method with the (sync modi!ier" you can use the (wait operator in the method. ( statement with the ,-ait operator suspends e'ecution o! the method until the awaited tas completes. The tas represents ongoing wor . 1hen the tas that8s associated with the ,-ait operator !inishes" e'ecution resumes in the same method. For more in!ormation" see Control Flow in (sync Programs (C9 and Visual Basic). ( tas returned by an (sync method may end in a !aulted state" indicating that it completed due to an unhandled e'ception. ( tas may also end in a canceled state" which results in an .perationCanceledException being thrown out o! the await e'pression. To catch either type o! e'ception" place the ,-ait e'pression that8s associated with the tas in a Try bloc " and catch the e'ception in the Catch bloc . (n e'ample is provided later in this topic. ( tas can be in a !aulted state because multiple e'ceptions were responsible !or its !aulting. For e'ample" the tas might be the result o! a call to Tas .1hen(ll. 1hen you await such a tas " the caught e'ception is only one o! the e'ceptions" and you can8t predict which e'ception will be caught. (n e'ample is provided later in this topic. (n ,-ait e'pression can8t be inside a Catch bloc or Finally bloc .

&terators
(n iterator !unction or /et accessor per!orms a custom iteration over a collection. (n iterator uses a 2ield statement to return each element o! the collection one at a time. 2ou call an iterator !unction by using a For ,ach...-e't Statement (Visual Basic). ( 0ield statement can be inside a Try bloc . ( Try bloc that contains a 0ield statement can have Catch bloc s" and can have a Finally bloc . See the :Try Bloc s in Visual Basic: section o! &terators (C9 and Visual Basic) !or an e'ample. ( 0ield statement cannot be inside a Catch bloc or a Finally bloc . &! the For Each body (outside o! the iterator !unction) throws an e'ception" a Catch bloc in the iterator !unction is not e'ecuted" but a Finally bloc in the iterator !unction is e'ecuted. ( Catch bloc inside an iterator !unction catches only e'ceptions that occur inside the iterator !unction.

Partial7Trust Situations
&n partial7trust situations" such as an application hosted on a networ share" Try...Catch...Finally does not catch security e'ceptions that occur be!ore the method that contains the call is invo ed. The !ollowing e'ample" when you put it on a server share and run !rom there" produces the error :System.Security.Security,'ception3 0e;uest Failed.: For more in!ormation about security e'ceptions" see the Security,'ception class. VB Try Process.Start!*http,00111.microsoft.com*% Catch ex As Exception 2s$"ox!*Can&t load We pa$e* - v Cr3f - ex.2essa$e% End Try

&n such a partial7trust situation" you have to put the Process.Start statement in a separate Su1. The initial call to the Su1

" of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

will !ail. This enables Try...Catch to catch it be!ore the Su1 that contains Process.Start is started and the security e'ception produced.

,'ample
The !ollowing e'ample illustrates the structure o! the Try...Catch...Finally statement. VB Pu lic Su TryExample!% & .eclare varia les. .im x As 'nte$er ) 4 .im y As 'nte$er ) 5 & Set up structured error handlin$. Try & Cause a *.ivide y 6ero* exception. x ) x 7 y & This statement does not execute ecause pro$ram & control passes to the Catch loc8 1hen the & exception occurs. 2essa$e"ox.Sho1!*end of Try loc8*% Catch ex As Exception & Sho1 the exception&s messa$e. 2essa$e"ox.Sho1!ex.2essa$e% & Sho1 the stac8 trace9 1hich is a list of methods & that are currently executin$. 2essa$e"ox.Sho1!*Stac8 Trace, * - v Cr3f - ex.Stac8Trace% Finally & This line executes 1hether or not the exception occurs. 2essa$e"ox.Sho1!*in Finally loc8*% End Try End Su

&n the !ollowing e'ample" the CreateException method throws a +ull)e#erenceException. The code that generates the e'ception is not in a Try bloc . There!ore" the CreateException method does not handle the e'ception. The /unSample method does handle the e'ception because the call to the CreateException method is in a Try bloc . The e'ample includes Catch statements !or several types o! e'ceptions" ordered !rom the most speci!ic to the most general. VB Pu lic Su /unSample!% Try CreateException!% Catch ex As System.'(.'(Exception & Code that reacts to '(Exception. Catch ex As +ull/eferenceException 2essa$e"ox.Sho1!*+ull/eferenceException, * - ex.2essa$e% 2essa$e"ox.Sho1!*Stac8 Trace, * - v Cr3f - ex.Stac8Trace% Catch ex As Exception & Code that reacts to any other exception.

, of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

End Try End Su Private Su CreateException!% & This code thro1s a +ull/eferenceException. .im o : ) +othin$ .im prop ) o :.+ame & This code also thro1s a +ull/eferenceException. &Thro1 +e1 +ull/eferenceException!*Somethin$ happened.*% End Su

The !ollowing e'ample shows how to use a Catch When statement to !ilter on a conditional e'pression. &! the conditional e'pression evaluates to True" the code in the Catch bloc runs. VB Private Su WhenExample!% .im i As 'nte$er ) 4 Try Thro1 +e1 Ar$umentException!% Catch e As (verflo1Exception When i ) 4 Console.Write3ine!*First handler*% Catch e As Ar$umentException When i ) ; Console.Write3ine!*Second handler*% Catch When i ) 4 Console.Write3ine!*Third handler*% End Try End Su & (utput, Third handler

The !ollowing e'ample has a TryCatch statement that is contained in a Try bloc . The inner Catch bloc throws an e'ception that has its "nnerException property set to the original e'ception. The outer Catch bloc reports its own e'ception and the inner e'ception. VB Private Su 'nnerExceptionExample!% Try Try & Set a reference to a Strin$"uilder. & The exception elo1 does not occur if the commented & out statement is used instead. .im s As System.Text.Strin$"uilder &.im s As +e1 System.Text.Strin$"uilder & Cause a +ull/eferenceException. s .Append!*text*% Catch ex As Exception & Thro1 a ne1 exception that has the inner exception & set to the ori$inal exception. Thro1 +e1 ApplicationException!*Somethin$ happened ,!*9 ex% End Try Catch ex< As Exception & Sho1 the exception.

! of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

Console.Write3ine!*Exception, * - ex<.2essa$e% Console.Write3ine!ex<.Stac8Trace% & Sho1 the inner exception9 if one is present. 'f ex<.'nnerException 's+ot +othin$ Then Console.Write3ine!*'nner Exception, * - ex<.'nnerException.2essa$e% Console.Write3ine!ex<.Stac8Trace% End 'f End Try End Su

The !ollowing e'ample illustrates e'ception handling !or async methods. To catch an e'ception that applies to an async tas " the ,-ait e'pression is in a Try bloc o! the caller" and the e'ception is caught in the Catch bloc . )ncomment the Thro1 +e1 Exception line in the e'ample to demonstrate e'ception handling. The e'ception is caught in the Catch bloc " the tas 8s "sFaulted property is set to True" and the tas 8s Exception."nnerException property is set to the e'ception. )ncomment the Thro1 +e1 (perationCancelledException line to demonstrate what happens when you cancel an asynchronous process. The e'ception is caught in the Catch bloc " and the tas 8s "sCanceled property is set to True. 5owever" under some conditions that don8t apply to this e'ample" "sFaulted is set to True and "sCanceled is set to False. VB Pu lic Async Function .oSomethin$Async!% As Tas8 .im theTas8 As Tas8!(f Strin$% ) .elayAsync!% Try .im result As Strin$ ) A1ait theTas8 .e u$.Write3ine!*/esult, * - result% Catch ex As Exception .e u$.Write3ine!*Exception 2essa$e, * - ex.2essa$e% End Try .e u$.Write3ine!*Tas8 'sCanceled, * - theTas8.'sCanceled% .e u$.Write3ine!*Tas8 'sFaulted, * - theTas8.'sFaulted% 'f theTas8.Exception 's+ot +othin$ Then .e u$.Write3ine!*Tas8 Exception 2essa$e, * theTas8.Exception.2essa$e% .e u$.Write3ine!*Tas8 'nner Exception 2essa$e, * theTas8.Exception.'nnerException.2essa$e% End 'f End Function Private Async Function .elayAsync!% As Tas8!(f Strin$% A1ait Tas8..elay!=55% & >ncomment each of the follo1in$ lines to & demonstrate exception handlin$. &Thro1 +e1 (perationCanceledException!*canceled*% &Thro1 +e1 Exception!*Somethin$ happened.*% /eturn *.one* End Function

& (utput 1hen no exception is thro1n in the a1aited method,

- of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

& & &

/esult, .one Tas8 'sCanceled, False Tas8 'sFaulted, False

& (utput 1hen an Exception is thro1n in the a1aited method, & Exception 2essa$e, Somethin$ happened. & Tas8 'sCanceled, False & Tas8 'sFaulted, True & Tas8 Exception 2essa$e, (ne or more errors occurred. & Tas8 'nner Exception 2essa$e, Somethin$ happened. & (utput 1hen an (perationCanceledException or Tas8CanceledException & is thro1n in the a1aited method, & Exception 2essa$e, canceled & Tas8 'sCanceled, True & Tas8 'sFaulted, False

The !ollowing e'ample illustrates e'ception handling where multiple tas s can result in multiple e'ceptions. The Try bloc has the ,-ait e'pression !or the tas that Tas .1hen(ll returned. The tas is complete when the three tas s to which Tas .1hen(ll is applied are complete. ,ach o! the three tas s causes an e'ception. The Catch bloc iterates through the e'ceptions" which are !ound in the Exception."nnerExceptions property o! the tas that Tas2.When,ll returned. VB Pu lic Async Function .o2ultipleAsync!% As Tas8 .im theTas8= As Tas8 ) ExcAsync!info,)*First Tas8*% .im theTas8< As Tas8 ) ExcAsync!info,)*Second Tas8*% .im theTas8? As Tas8 ) ExcAsync!info,)*Third Tas8*% .im allTas8s As Tas8 ) Tas8.WhenAll!theTas8=9 theTas8<9 theTas8?% Try A1ait allTas8s Catch ex As Exception .e u$.Write3ine!*Exception, * - ex.2essa$e% .e u$.Write3ine!*Tas8 'sFaulted, * - allTas8s.'sFaulted% For Each inEx 'n allTas8s.Exception.'nnerExceptions .e u$.Write3ine!*Tas8 'nner Exception, * @ inEx.2essa$e% +ext End Try End Function Private Async Function ExcAsync!info As Strin$% As Tas8 A1ait Tas8..elay!=55% Thro1 +e1 Exception!*ErrorA* - info% End Function & (utput, & Exception, ErrorAFirst Tas8 & Tas8 'sFaulted, True & Tas8 'nner Exception, ErrorAFirst Tas8 & Tas8 'nner Exception, ErrorASecond Tas8 & Tas8 'nner Exception, ErrorAThird Tas8

. of &

'/'(/'(%" ':'" )*

Try...Catch...Finally Statement (Visual Basic)

http://msdn.microsoft.com/en-us/library/f !t"!t#.asp$

See (lso
0e!erence
,rr ,'it Statement (Visual Basic) $n ,rror Statement (Visual Basic) ,'ception Throw Statement (Visual Basic)

Concepts
Best Practices !or )sing Code Snippets ,'ception 5andling (Tas Parallel 4ibrary)

< =>.? %icroso!t. (ll rights reserved.

& of &

'/'(/'(%" ':'" )*

Você também pode gostar