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 ...

Get C# Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.