Try...Catch...Finally 陳述式 (Visual Basic)Try...Catch...Finally Statement (Visual Basic)

提供處理部分或所有可能的錯誤時仍在執行程式碼中指定的程式碼區塊,可能發生的方法。Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.

語法Syntax

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

組件Parts

詞彙Term 定義Definition
tryStatements 選擇性。Optional. 可能發生錯誤的陳述式。Statement(s) where an error can occur. 可以是複合陳述式。Can be a compound statement.
Catch 選擇性。Optional. 多個Catch允許的區塊。Multiple Catch blocks permitted. 如果發生例外狀況處理時Try區塊,每個Catch陳述式會檢查以判斷是否與處理的例外狀況的文字順序exception代表已擲回的例外狀況。If an exception occurs when processing the Try block, each Catch statement is examined in textual order to determine whether it handles the exception, with exception representing the exception that has been thrown.
exception 選擇性。Optional. 任何變數名稱。Any variable name. exception 的初始值就是擲回之錯誤的值。The initial value of exception is the value of the thrown error. 搭配Catch來指定錯誤攔截。Used with Catch to specify the error caught. 如果省略,Catch陳述式攔截任何例外狀況。If omitted, the Catch statement catches any exception.
type 選擇性。Optional. 指定的類別篩選器類型。Specifies the type of class filter. 如果值exception所指定型別的type或衍生的型別中,識別碼會成為繫結至例外狀況物件。If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object.
When 選擇性。Optional. ACatch陳述式搭配When子句會攔截例外狀況時,才expression評估為TrueA Catch statement with a When clause catches exceptions only when expression evaluates to True. AWhen子句會檢查例外狀況的類型之後,才會套用和expression可能表示例外狀況的識別項參考。A When clause is applied only after checking the type of the exception, and expression may refer to the identifier representing the exception.
expression 選擇性。Optional. 必須是隱含地轉換成BooleanMust be implicitly convertible to Boolean. 描述泛型篩選的任何運算式。Any expression that describes a generic filter. 通常用來篩選出的錯誤號碼。Typically used to filter by error number. 搭配When關鍵字來指定用以在攔截到錯誤的情況。Used with When keyword to specify circumstances under which the error is caught.
catchStatements 選擇性。Optional. 陳述式來處理發生在相關聯的錯誤Try區塊。Statement(s) to handle errors that occur in the associated Try block. 可以是複合陳述式。Can be a compound statement.
Exit Try 選擇性。Optional. 中斷的關鍵字Try...Catch...Finally結構。Keyword that breaks out of the Try...Catch...Finally structure. 使用程式碼之後立即繼續執行End Try陳述式。Execution resumes with the code immediately following the End Try statement. Finally仍可執行陳述式。The Finally statement will still be executed. 中不允許Finally區塊。Not allowed in Finally blocks.
Finally 選擇性。Optional. AFinally當執行離開的任何部分時,就會永遠執行區塊Try...Catch陳述式。A Finally block is always executed when execution leaves any part of the Try...Catch statement.
finallyStatements 選擇性。Optional. 所有其他錯誤處理都發生之後執行的陳述式。Statement(s) that are executed after all other error processing has occurred.
End Try 終止Try...Catch...Finally結構。Terminates the Try...Catch...Finally structure.

備註Remarks

如果您預期特定的例外狀況可能會發生在特定的一段程式碼期間,將程式碼置於Try封鎖,並使用Catch保留控制項,以及處理例外狀況發生時的區塊。If you expect that a particular exception might occur during a particular section of code, put the code in a Try block and use a Catch block to retain control and handle the exception if it occurs.

ATry…Catch陳述式組成Try區塊後面接著一或多個Catch子句,指定各種不同例外狀況處理常式。A Try…Catch statement consists of a Try block followed by one or more Catch clauses, which specify handlers for various exceptions. 當擲回例外狀況Try區塊中,Visual Basic 會尋找Catch處理例外狀況的陳述式。When an exception is thrown in a Try block, Visual Basic looks for the Catch statement that handles the exception. 如果比對Catch找不到陳述式、 Visual Basic 會檢查呼叫目前的方法,依此類推的呼叫堆疊上的方法。If a matching Catch statement is not found, Visual Basic examines the method that called the current method, and so on up the call stack. 如果沒有Catch找不到區塊、 Visual Basic 向使用者顯示未處理的例外狀況訊息,並停止執行程式。If no Catch block is found, Visual Basic displays an unhandled exception message to the user and stops execution of the program.

您可以使用一個以上Catch中的陳述式Try…Catch陳述式。You can use more than one Catch statement in a Try…Catch statement. 如果您這麼做,順序Catch子句很重要,因為它們會依順序檢查。If you do this, the order of the Catch clauses is significant because they are examined in order. 在較不特定的例外狀況之前攔截較特定的例外狀況。Catch the more specific exceptions before the less specific ones.

下列Catch陳述式的條件是最不特定,並會攔截所有例外狀況衍生自Exception類別。The following Catch statement conditions are the least specific, and will catch all exceptions that derive from the Exception class. 您通常應該使用其中一個這些變化最後Catch中區塊Try...Catch...Finally結構之後攔截您預期的所有特定例外狀況。You should ordinarily use one of these variations as the last Catch block in the Try...Catch...Finally structure, after catching all the specific exceptions you expect. 控制流程可以永遠無法觸達Catch遵循其中一個這些變化的區塊。Control flow can never reach a Catch block that follows either of these variations.

  • typeException,例如: Catch ex As ExceptionThe type is Exception, for example: Catch ex As Exception

  • 該陳述式沒有exception變數,例如: CatchThe statement has no exception variable, for example: Catch

Try…Catch…Finally陳述式巢狀方式置於另一個Try區塊中,Visual Basic 會先檢查每個Catch陳述式中最內側Try區塊。When a Try…Catch…Finally statement is nested in another Try block, Visual Basic first examines each Catch statement in the innermost Try block. 如果沒有相符Catch找到陳述式中,搜尋會繼續Catch陳述式的外部Try…Catch…Finally區塊。If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Try…Catch…Finally block.

從區域變數Try區塊中未提供Catch封鎖,因為它們是不同的區塊。Local variables from a Try block are not available in a Catch block because they are separate blocks. 如果您想要使用多個區塊中的變數,將外部變數宣告Try...Catch...Finally結構。If you want to use a variable in more than one block, declare the variable outside the Try...Catch...Finally structure.

提示

Try…Catch…Finally陳述式可從 IntelliSense 程式碼片段。The Try…Catch…Finally statement is available as an IntelliSense code snippet. 在程式碼片段管理員 中,依序展開程式碼模式-If、 For Each、 Try Catch、 屬性等等,然後錯誤處理 (例外狀況)In the Code Snippets Manager, expand Code Patterns - If, For Each, Try Catch, Property, etc, and then Error Handling (Exceptions). 如需詳細資訊,請參閱程式碼片段For more information, see Code Snippets.

Finally 區塊Finally block

如果您有一或多個您在結束前必須執行的陳述式Try結構,請使用Finally區塊。If you have one or more statements that must run before you exit the Try structure, use a Finally block. 控制權會傳遞給Finally封鎖之前它會傳遞共Try…Catch結構。Control passes to the Finally block just before it passes out of the Try…Catch structure. 這是 true,即使在任何一處發生例外狀況Try結構。This is true even if an exception occurs anywhere inside the Try structure.

AFinally區塊在執行任何程式碼必須執行,即使發生例外狀況是很有用。A Finally block is useful for running any code that must execute even if there is an exception. 控制權會傳遞給Finally不論區塊Try...Catch區塊結束。Control is passed to the Finally block regardless of how the Try...Catch block exits.

中的程式碼Finally封鎖執行,即使您的程式碼遇到Return中的陳述式TryCatch區塊。The code in a Finally block runs even if your code encounters a Return statement in a Try or Catch block. 控制項不會從傳遞Try或是Catch封鎖對應Finally封鎖在下列情況:Control does not pass from a Try or Catch block to the corresponding Finally block in the following cases:

若要明確地傳輸到執行無效Finally區塊。It is not valid to explicitly transfer execution into a Finally block. 傳送執行共Finally區塊不是有效的除了透過例外狀況。Transferring execution out of a Finally block is not valid, except through an exception.

如果Try陳述式未包含至少一個Catch區塊中,它必須包含Finally區塊。If a Try statement does not contain at least one Catch block, it must contain a Finally block.

提示

如果您不需要攔截特定的例外狀況Using陳述式的行為類似Try…Finally區塊,以及保證可供使用的資源,不論您如何結束區塊。If you do not have to catch specific exceptions, the Using statement behaves like a Try…Finally block, and guarantees disposal of the resources, regardless of how you exit the block. 這是即使有未處理的例外狀況,則為 true。This is true even with an unhandled exception. 如需詳細資訊,請參閱 Using 陳述式For more information, see Using Statement.

例外狀況的引數Exception argument

Catch區塊exception引數是的執行個體Exception類別或衍生自類別Exception類別。The Catch block exception argument is an instance of the Exception class or a class that derives from the Exception class. Exception類別執行個體對應至中發生之錯誤Try區塊。The Exception class instance corresponds to the error that occurred in the Try block.

屬性Exception物件協助識別原因和例外狀況的位置。The properties of the Exception object help to identify the cause and location of an exception. 比方說,StackTrace屬性清單導致例外狀況,協助您尋找程式碼中發生錯誤的呼叫的方法。For example, the StackTrace property lists the called methods that led to the exception, helping you find where the error occurred in the code. Message 傳回描述例外狀況的訊息。Message returns a message that describes the exception. HelpLink 會傳回相關聯的說明檔的連結。HelpLink returns a link to an associated Help file. InnerException 會傳回Exception造成目前例外狀況,或它的物件會傳回Nothing如果沒有任何原始ExceptionInnerException returns the Exception object that caused the current exception, or it returns Nothing if there is no original Exception.

使用 Try 時的考量...Catch 陳述式Considerations when using a Try…Catch statement

使用Try…Catch只表示發生異常或非預期的程式事件的陳述式。Use a Try…Catch statement only to signal the occurrence of unusual or unanticipated program events. 這樣做的原因包括:Reasons for this include the following:

  • 在執行階段攔截例外狀況會建立額外的負荷,並可能會低於預先檢查,以避免發生例外狀況。Catching exceptions at runtime creates additional overhead, and is likely to be slower than pre-checking to avoid exceptions.

  • 如果Catch無法正確處理區塊、 例外狀況可能不會報告正確的使用者。If a Catch block is not handled correctly, the exception might not be reported correctly to users.

  • 例外狀況處理可讓程式更複雜。Exception handling makes a program more complex.

您不一定需要Try…Catch陳述式來檢查是否有可能發生的狀況。You do not always need a Try…Catch statement to check for a condition that is likely to occur. 下列範例會檢查檔案是否存在然後再嘗試開啟它。The following example checks whether a file exists before trying to open it. 這可減少需要攔截所擲回的例外狀況OpenText方法。This reduces the need for catching an exception thrown by the OpenText method.

Private Sub TextFileExample(ByVal filePath As String)

    ' Verify that the file exists.
    If System.IO.File.Exists(filePath) = False Then
        Console.Write("File Not Found: " & filePath)
    Else
        ' Open the text file and display its contents.
        Dim sr As System.IO.StreamReader =
            System.IO.File.OpenText(filePath)

        Console.Write(sr.ReadToEnd)

        sr.Close()
    End If
End Sub

請確定該程式碼中的Catch區塊可以正確地報告給使用者,例外狀況,不論是透過安全執行緒記錄或適當的訊息。Ensure that code in Catch blocks can properly report exceptions to users, whether through thread-safe logging or appropriate messages. 否則,您可能會維持未知例外狀況。Otherwise, exceptions might remain unknown.

非同步方法Async methods

如果您將標記的方法非同步修飾詞,您可以使用Await方法中的運算子。If you mark a method with the Async modifier, you can use the Await operator in the method. 陳述式加上Await運算子會暫停執行方法,直到等候的工作完成。A statement with the Await operator suspends execution of the method until the awaited task completes. 工作代表進行中的工作。The task represents ongoing work. 當相關聯的工作Await運算子完成時,執行會繼續在相同的方法。When the task that's associated with the Await operator finishes, execution resumes in the same method. 如需詳細資訊,請參閱 < 非同步程式中的控制流程For more information, see Control Flow in Async Programs.

非同步方法所傳回的工作可能會處於錯誤狀態,指出它完成因為發生未處理的例外狀況。A task returned by an Async method may end in a faulted state, indicating that it completed due to an unhandled exception. 工作可能也會結束取消的狀態,導致OperationCanceledException擲出 await 運算式。A task may also end in a canceled state, which results in an OperationCanceledException being thrown out of the await expression. 若要攔截的例外狀況的其中一個類型,請將Await運算式中的工作與相關聯Try區塊中,並攔截例外狀況中的Catch區塊。To catch either type of exception, place the Await expression that's associated with the task in a Try block, and catch the exception in the Catch block. 本主題稍後提供的範例。An example is provided later in this topic.

工作可能處於錯誤狀態,因為多個例外狀況會負責其錯誤。A task can be in a faulted state because multiple exceptions were responsible for its faulting. 例如,工作可能是對 Task.WhenAll 呼叫的結果。For example, the task might be the result of a call to Task.WhenAll. 當您等候這類工作時,攔截的例外狀況只是其中一個例外狀況,而且您無法預測會攔截到例外狀況。When you await such a task, the caught exception is only one of the exceptions, and you can't predict which exception will be caught. 本主題稍後提供的範例。An example is provided later in this topic.

Await運算式不能是內Catch區塊或Finally區塊。An Await expression can't be inside a Catch block or Finally block.

迭代器Iterators

迭代器函式或Get存取子會對集合執行自訂反覆項目。An iterator function or Get accessor performs a custom iteration over a collection. 迭代器會使用產生陳述式來傳回一次一個集合的每個項目。An iterator uses a Yield statement to return each element of the collection one at a time. 您可以使用呼叫 iterator 函式每個...下一個陳述式You call an iterator function by using a For Each...Next Statement.

AYield陳述式可以位於Try區塊。A Yield statement can be inside a Try block. ATry包含區塊Yield陳述式可以有Catch區塊中使用,而且可以有Finally區塊。A Try block that contains a Yield statement can have Catch blocks, and can have a Finally block. 請參閱 「 嘗試區塊在 Visual Basic 」 一節迭代器的範例。See the "Try Blocks in Visual Basic" section of Iterators for an example.

AYield陳述式不能內Catch區塊或Finally區塊。A Yield statement cannot be inside a Catch block or a Finally block.

如果For Each主體 (之外的迭代器函式) 會擲回的例外狀況,Catch迭代器函式中的區塊不會執行,但Finally執行迭代器函式中的區塊。If the For Each body (outside of the iterator function) throws an exception, a Catch block in the iterator function is not executed, but a Finally block in the iterator function is executed. ACatch迭代器函式內的區塊會攔截在迭代器函式內所發生的例外狀況。A Catch block inside an iterator function catches only exceptions that occur inside the iterator function.

部分信任情況下Partial-trust situations

在部分信任情況下,應用程式裝載在網路共用,例如Try...Catch...Finally不會攔截之前叫用包含呼叫方法時,發生安全性例外狀況。In partial-trust situations, such as an application hosted on a network share, Try...Catch...Finally does not catch security exceptions that occur before the method that contains the call is invoked. 下列範例中,當您將它放在伺服器共用,並從該處執行會產生錯誤 「 System.Security.SecurityException:要求失敗。 」The following example, when you put it on a server share and run from there, produces the error "System.Security.SecurityException: Request Failed." 如需安全性例外狀況的詳細資訊,請參閱SecurityException類別。For more information about security exceptions, see the SecurityException class.

Try
    Process.Start("http://www.microsoft.com")
Catch ex As Exception
    MsgBox("Can't load Web page" & vbCrLf & ex.Message)
End Try

在這類的部分信任情況下,您必須將放Process.Start在個別的陳述式SubIn such a partial-trust situation, you have to put the Process.Start statement in a separate Sub. 若要在初次呼叫Sub將會失敗。The initial call to the Sub will fail. 這可讓Try...Catch攔截之前Sub包含Process.Start已啟動,並產生安全性例外狀況。This enables Try...Catch to catch it before the Sub that contains Process.Start is started and the security exception produced.

範例Examples

請嘗試結構...Catch...最後The structure of Try...Catch...Finally

下列範例說明結構Try...Catch...Finally陳述式。The following example illustrates the structure of the Try...Catch...Finally statement.

Public Sub TryExample()
    ' Declare variables.
    Dim x As Integer = 5
    Dim y As Integer = 0

    ' Set up structured error handling.
    Try
        ' Cause a "Divide by Zero" exception.
        x = x \ y

        ' This statement does not execute because program
        ' control passes to the Catch block when the
        ' exception occurs.
        MessageBox.Show("end of Try block")
    Catch ex As Exception
        ' Show the exception's message.
        MessageBox.Show(ex.Message)

        ' Show the stack trace, which is a list of methods
        ' that are currently executing.
        MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
    Finally
        ' This line executes whether or not the exception occurs.
        MessageBox.Show("in Finally block")
    End Try
End Sub

從 Try 區塊中呼叫的方法中的例外狀況Exception in a method called from a Try block

在下列範例中,CreateException方法會擲回NullReferenceExceptionIn the following example, the CreateException method throws a NullReferenceException. 不會產生例外狀況的程式碼是Try區塊。The code that generates the exception is not in a Try block. 因此,CreateException方法不會處理例外狀況。Therefore, the CreateException method does not handle the exception. RunSample方法未處理例外狀況,因為呼叫CreateException方法是在Try區塊。The RunSample method does handle the exception because the call to the CreateException method is in a Try block.

此範例也包含Catch陳述式中的數種類型的例外狀況,排序從最特定到最普遍。The example includes Catch statements for several types of exceptions, ordered from the most specific to the most general.

Public Sub RunSample()
    Try
        CreateException()
    Catch ex As System.IO.IOException
        ' Code that reacts to IOException.
    Catch ex As NullReferenceException
        MessageBox.Show("NullReferenceException: " & ex.Message)
        MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
    Catch ex As Exception
        ' Code that reacts to any other exception.
    End Try
End Sub

Private Sub CreateException()
    ' This code throws a NullReferenceException.
    Dim obj = Nothing
    Dim prop = obj.Name

    ' This code also throws a NullReferenceException.
    'Throw New NullReferenceException("Something happened.")
End Sub

當 Catch 陳述式The Catch When statement

下列範例示範如何使用Catch When篩選條件運算式的陳述式。The following example shows how to use a Catch When statement to filter on a conditional expression. 如果條件運算式評估為True中的程式碼Catch封鎖執行。If the conditional expression evaluates to True, the code in the Catch block runs.

Private Sub WhenExample()
    Dim i As Integer = 5

    Try
        Throw New ArgumentException()
    Catch e As OverflowException When i = 5
        Console.WriteLine("First handler")
    Catch e As ArgumentException When i = 4
        Console.WriteLine("Second handler")
    Catch When i = 5
        Console.WriteLine("Third handler")
    End Try
End Sub
' Output: Third handler

巢狀的 Try 陳述式Nested Try statements

下列範例具有Try…Catch陳述式中包含Try區塊。The following example has a Try…Catch statement that is contained in a Try block. 內部Catch區塊擲回例外狀況有其InnerException屬性設為原始的例外狀況。The inner Catch block throws an exception that has its InnerException property set to the original exception. 外部Catch區塊會報告它自己的例外狀況以及內部例外狀況。The outer Catch block reports its own exception and the inner exception.

Private Sub InnerExceptionExample()
    Try
        Try
            ' Set a reference to a StringBuilder.
            ' The exception below does not occur if the commented
            ' out statement is used instead.
            Dim sb As System.Text.StringBuilder
            'Dim sb As New System.Text.StringBuilder

            ' Cause a NullReferenceException.
            sb.Append("text")
        Catch ex As Exception
            ' Throw a new exception that has the inner exception
            ' set to the original exception.
            Throw New ApplicationException("Something happened :(", ex)
        End Try
    Catch ex2 As Exception
        ' Show the exception.
        Console.WriteLine("Exception: " & ex2.Message)
        Console.WriteLine(ex2.StackTrace)

        ' Show the inner exception, if one is present.
        If ex2.InnerException IsNot Nothing Then
            Console.WriteLine("Inner Exception: " & ex2.InnerException.Message)
            Console.WriteLine(ex2.StackTrace)
        End If
    End Try
End Sub

非同步方法的例外狀況處理Exception handling for async methods

下列範例說明非同步方法的例外狀況處理。The following example illustrates exception handling for async methods. 若要擷取套用至一項非同步工作,例外狀況Await運算式是在Try的呼叫端和例外狀況區塊會攔截在Catch區塊。To catch an exception that applies to an async task, the Await expression is in a Try block of the caller, and the exception is caught in the Catch block.

取消註解範例中的 Throw New Exception 行來示範例外狀況處理。Uncomment the Throw New Exception line in the example to demonstrate exception handling. 中攔截例外狀況Catch封鎖工作的IsFaulted屬性設定為True,以及使用 「 工作Exception.InnerException屬性設定為例外狀況。The exception is caught in the Catch block, the task's IsFaulted property is set to True, and the task's Exception.InnerException property is set to the exception.

取消註解 Throw New OperationCancelledException 行來示範取消非同步處理序時會發生的情況。Uncomment the Throw New OperationCancelledException line to demonstrate what happens when you cancel an asynchronous process. 在攔截例外狀況Catch區塊,以及工作IsCanceled屬性設定為TrueThe exception is caught in the Catch block, and the task's IsCanceled property is set to True. 不過,在未套用至這個範例中,某些情況下IsFaulted設定為TrueIsCanceled設定為FalseHowever, under some conditions that don't apply to this example, IsFaulted is set to True and IsCanceled is set to False.

Public Async Function DoSomethingAsync() As Task
    Dim theTask As Task(Of String) = DelayAsync()

    Try
        Dim result As String = Await theTask
        Debug.WriteLine("Result: " & result)
    Catch ex As Exception
        Debug.WriteLine("Exception Message: " & ex.Message)
    End Try

    Debug.WriteLine("Task IsCanceled: " & theTask.IsCanceled)
    Debug.WriteLine("Task IsFaulted:  " & theTask.IsFaulted)
    If theTask.Exception IsNot Nothing Then
        Debug.WriteLine("Task Exception Message: " &
            theTask.Exception.Message)
        Debug.WriteLine("Task Inner Exception Message: " &
            theTask.Exception.InnerException.Message)
    End If
End Function

Private Async Function DelayAsync() As Task(Of String)
    Await Task.Delay(100)

    ' Uncomment each of the following lines to
    ' demonstrate exception handling.

    'Throw New OperationCanceledException("canceled")
    'Throw New Exception("Something happened.")
    Return "Done"
End Function


' Output when no exception is thrown in the awaited method:
'   Result: Done
'   Task IsCanceled: False
'   Task IsFaulted:  False

' Output when an Exception is thrown in the awaited method:
'   Exception Message: Something happened.
'   Task IsCanceled: False
'   Task IsFaulted:  True
'   Task Exception Message: One or more errors occurred.
'   Task Inner Exception Message: Something happened.

' Output when an OperationCanceledException or TaskCanceledException
' is thrown in the awaited method:
'   Exception Message: canceled
'   Task IsCanceled: True
'   Task IsFaulted:  False

在非同步方法中的多個例外狀況處理Handling multiple exceptions in async methods

下列範例說明多項工作可能會導致多個例外狀況的例外狀況處理。The following example illustrates exception handling where multiple tasks can result in multiple exceptions. Try區塊Await工作的運算式,Task.WhenAll傳回。The Try block has the Await expression for the task that Task.WhenAll returned. 工作已完成的三個工作的Task.WhenAll套用都已完成。The task is complete when the three tasks to which Task.WhenAll is applied are complete.

這三個工作都會造成例外狀況。Each of the three tasks causes an exception. Catch區塊會逐一查看的例外狀況中找到Exception.InnerExceptions工作的屬性,Task.WhenAll傳回。The Catch block iterates through the exceptions, which are found in the Exception.InnerExceptions property of the task that Task.WhenAll returned.

Public Async Function DoMultipleAsync() As Task
    Dim theTask1 As Task = ExcAsync(info:="First Task")
    Dim theTask2 As Task = ExcAsync(info:="Second Task")
    Dim theTask3 As Task = ExcAsync(info:="Third Task")

    Dim allTasks As Task = Task.WhenAll(theTask1, theTask2, theTask3)

    Try
        Await allTasks
    Catch ex As Exception
        Debug.WriteLine("Exception: " & ex.Message)
        Debug.WriteLine("Task IsFaulted: " & allTasks.IsFaulted)
        For Each inEx In allTasks.Exception.InnerExceptions
            Debug.WriteLine("Task Inner Exception: " + inEx.Message)
        Next
    End Try
End Function

Private Async Function ExcAsync(info As String) As Task
    Await Task.Delay(100)

    Throw New Exception("Error-" & info)
End Function

' Output:
'   Exception: Error-First Task
'   Task IsFaulted: True
'   Task Inner Exception: Error-First Task
'   Task Inner Exception: Error-Second Task
'   Task Inner Exception: Error-Third Task

另請參閱See also