If you are a programmer, I’m sure you have used try/catch blocks in your code to hopefully eliminate any dreadful unhandled exceptions. We all know they usually happen only when giving a presentation and that’s no good! You could go by throwing generic exceptions all day long…
-
throw new Exception
(“Hey, you broke my program :(”);
That’s a bit generic though. This is where custom exceptions come in. It’s more intuitive and much less generic than throwing Exception() every time. It will also give you better control over choosing what to do when any exception is thrown. Instead of having one catch block, you’ll have the catch blocks for your custom exceptions with the generic Exception() last to catch anything that got past.
First thing you’ll need to do is create a Windows Library project. I named mine CustomExceptions.

When the new project is open, you’ll have a file called Class1.cs which you can rename to the name of the exception you are going to create. When you do this, you will see a window like this:

Just click the Yes button and your class name will change throughout your project. Now we’re ready to do the actual coding. When creating custom exceptions, we must extend the ApplicationException class.
-
public class IllegalInputException : ApplicationException
-
{
-
}
Now we need to create the instance variables to be used in your exception. We’ll need one for the severity level, one for the log level, one for the inner exception and one for the message.
-
private int severityLevelOfException;
-
private int logLevelOfException;
-
private Exception innerException;
-
private string customMessage;
The severity and log levels allow you to give a bit more information about the type and severity of the exception you are throwing. If your exception was caused by another exception, it will store the original exception data as the inner exception. Last, the custom message is what you put in it to be used when it is caught. Read the rest of this entry »