throw

Throws a user-defined exception.

Syntax

throw expression

Parameters

Parameter Description
expression The value to throw.

Description

Use the throw statement to throw an exception. When you throw an exception, an expression specifies the value of the exception. The following code throws several exceptions.

Examples

Example 1. Throw an object

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.

Example 2. Throw an object

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

Example 3. Rethrow an exception

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

See also

try...catch

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.