ILGenerator.ThrowException Method
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Emits an instruction to throw an exception.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- excType
- Type: System.Type
The class of the type of exception to throw.
| Exception | Condition |
|---|---|
| ArgumentException | excType is not the Exception class or a derived class of Exception. -or- The type does not have a default constructor. |
| ArgumentNullException | excType is Nothing. |
The following example demonstrates the use of ThrowException to throw an exception with a default message. This code is part of a larger example provided for the BeginExceptionBlock method.
' Begin the try/catch/finally block. The label is used to leave the ' block. Dim exTryCatchFinally As Label = adderIL.BeginExceptionBlock() ' Load the first argument and the integer value 100 onto the execution ' stack, and test whether the argument is greater than 100. The result is ' now on the execution stack. ' adderIL.Emit(OpCodes.Ldarg_0) adderIL.Emit(OpCodes.Ldc_I4_S, 100) adderIL.Emit(OpCodes.Cgt) ' Test whether the second argument is greater than 100. Both results are ' now on the execution stack. ' adderIL.Emit(OpCodes.Ldarg_1) adderIL.Emit(OpCodes.Ldc_I4_S, 100) adderIL.Emit(OpCodes.Cgt) ' Perform a logical OR on the two results, and branch to the 'succeeded' ' label if the result is true. adderIL.Emit(OpCodes.Or) adderIL.Emit(OpCodes.Brfalse, succeeded) ' If one of the arguments was greater than 100, throw an OverflowException. adderIL.ThrowException(overflowType) ' This example uses the ThrowException method, which uses the default ' constructor of the specified exception type to create the exception. If you ' want to specify your own message, you must use a different constructor; ' replace the ThrowException method call with code like that shown below, ' which creates the exception and throws it. ' ' Load the message, which is the argument for the constructor, onto the ' execution stack. Execute Newobj, with the OverflowException constructor ' that takes a string. This pops the message off the stack, and pushes the ' new exception onto the stack. The Throw instruction pops the exception off ' the stack and throws it. 'adderIL.Emit(OpCodes.Ldstr, "DoAdd does not accept values over 100.") 'adderIL.Emit(OpCodes.Newobj, _ ' overflowType.GetConstructor(New Type() { GetType(String) })) 'adderIL.Emit(OpCodes.Throw) ' If both arguments are less than or equal to 100, execution continues ' here. adderIL.MarkLabel(succeeded)