Throw 陳述式 (Visual Basic)Throw Statement (Visual Basic)

在程式中擲回例外狀況。Throws an exception within a procedure.

語法Syntax

Throw [ expression ]

組件Part

expression
提供要擲回之例外狀況的相關資訊。Provides information about the exception to be thrown. 如果位於Catch語句中, 則為選擇性, 否則為必要項。Optional when residing in a Catch statement, otherwise required.

備註Remarks

語句會擲回例外狀況, 您可以處理結構化例外狀況處理常式Try代碼 (... Throw``Catch...) 或非結構化例外狀況處理On Error GoTo程式碼 ()。 FinallyThe Throw statement throws an exception that you can handle with structured exception-handling code (Try...Catch...Finally) or unstructured exception-handling code (On Error GoTo). 您可以使用Throw語句來攔截程式碼內的錯誤, 因為 Visual Basic 會向上移動呼叫堆疊, 直到找到適當的例外狀況處理常式代碼為止。You can use the Throw statement to trap errors within your code because Visual Basic moves up the call stack until it finds the appropriate exception-handling code.

沒有運算式的Catch Catch語句只能在語句中使用, 在此情況下, 語句會重新擲回目前正由語句處理的例外狀況。 ThrowA Throw statement with no expression can only be used in a Catch statement, in which case the statement rethrows the exception currently being handled by the Catch statement.

語句會重設expression例外狀況的呼叫堆疊。 ThrowThe Throw statement resets the call stack for the expression exception. 如果expression未提供, 則會將呼叫堆疊保持不變。If expression is not provided, the call stack is left unchanged. 您可以透過StackTrace屬性存取例外狀況的呼叫堆疊。You can access the call stack for the exception through the StackTrace property.

範例Example

下列程式碼會使用Throw語句來擲回例外狀況:The following code uses the Throw statement to throw an exception:

' Throws a new exception.
Throw New System.Exception("An exception has occurred.")

另請參閱See also