Information Technology Reference
In-Depth Information
Throwing Exceptions
You can make your code explicitly raise an exception by using the throw statement. The syntax
for the throw statement is the following:
throw ExceptionObject ;
For example, the following code defines a method called PrintArg that takes a string argu-
ment and prints it out. Inside the try block, it first checks to make sure that the argument is not
null . If it is, it creates an ArgumentNullException instance and throws it. The exception instance
is caught in the catch statement, and the error message is printed. Main calls the method twice:
once with a null argument, and then with a valid argument.
class MyClass
{
public static void PrintArg(string arg)
{
try
{
if (arg == null)
{
ArgumentNullException MyEx = new ArgumentNullException();
throw MyEx;
}
Console.WriteLine(arg);
}
catch (ArgumentNullException e)
{
Console.WriteLine("Message: {0}", e.Message);
}
}
}
Search WWH ::




Custom Search