O'Reilly logo

C# Primer Plus by Klaus Michelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

throw: Explicitly Throwing Exceptions

In the previous sections, we have experienced the runtime's ability to automatically throw an exception when an abnormal condition arises. With the throw keyword, you can also throw an exception explicitly in your code, as in the following line:

throw new System.Exception();

This line creates and throws a new exception object of class System.Exception. You can alternatively provide a suitable string argument to the new object as follows:

throw new System.Exception("Invalid set of parameters");

This string can be accessed via the exception object's Message property presented earlier.

You can only throw objects that are of class System.Exception or a subclass thereof.

An explicitly thrown exception object ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required