Home > C#, Exceptions, Learn C# > Learn C# – Handling Exceptions (4) – Custom Exceptions

Learn C# – Handling Exceptions (4) – Custom Exceptions

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Handling Exceptions – Part 3 – Throwing Exceptions
  4. Handling Exceptions – Part 4 – Custom Exceptions

We met some common exception classes till now, and we even experienced throwing those exceptions by ourselves. That’s not always the case – we might want from time to time to throw our own exceptions, that will describe our own errors. For that purpose we should take a look first in the Exception class.

The Exception class

The basic Exception class is very simple, and contains some important properties:

  • Message – Contains details about the thrown exception.
  • Stack Trace – Contains details about all the methods involved.
  • InnerException – Sometimes contains details about the encapsulated exception.

There are some others, but those are the most useful. The constructor of the Exception class can accept custom message, so we can use that in order to supply our own exception:

void RegisterStudent(int age)
{
if (age < 18)
throw new Exception("Student can't be younger than 18 years old!");
}

This solution can feet our needs, but we usually don’t want to rely on strings to distinguish between exceptions. We will prefer something more strongly typed.

Custom Exceptions

The second solution for our desire will be to create custom exceptions. Custom exceptions are very simple to create, and it has only one rule: Inherit the base Exception class (or one of its childs). You can add whatever properties you want to your custom exception class, and use whatever constructor you’d like in the base class. Sometimes you won’t add any property at all – by creating specific type to describe the exception it might be enough. Let’s declare one:

public class StudentAgeException:Exception
{
public StudentAgeException(int age)
:base ("Age "+ age+" is not allowed. student age should be at least 18 years old")
{

}
}

And now we’ll use it:

void RegisterStudent(int age)
{
if (age < 18)
throw new StudentAgeException(age);
}

In the above example we declare new custom exception, that accept int parameter in its constructor and pass a message to the base constructor describing the issue. Whoever get’s the exception don’t need to rely on the message to understand the problem, since the problem is also identified by the type of the exception itself. That way is much more strongly typed and safe, since the caller can now create specific catch block to catch only StudentAgeException, and handle this exception in more specific way.

In the Next post we’ll describe the finally block, which will be the last part of our series.

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment