ILGenerator.ThrowException Method

Emits an instruction to throw an exception.

Namespace:  System.Reflection.Emit
Assembly:  mscorlib (in mscorlib.dll)

public virtual void ThrowException(
	Type excType


Type: System.Type
The class of the type of exception to throw.


excType is not the Exception class or a derived class of Exception.


The type does not have a default constructor.


excType is null.

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.
Label exTryCatchFinally = 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.Ldc_I4_S, 100);

// Test whether the second argument is greater than 100. Both results are
// now on the execution stack.
adderIL.Emit(OpCodes.Ldc_I4_S, 100);

// Perform a logical OR on the two results, and branch to the 'succeeded'
// label if the result is true.
adderIL.Emit(OpCodes.Brfalse, succeeded);

// If one of the arguments was greater than 100, throw an OverflowException. 

// 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[] { typeof(String) }));

// If both arguments are less than or equal to 100, execution continues 
// here.


Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Ajouts de la communauté