C# Custom Exception

Create custom exceptions which are then added to existing try catch blocks (above the general exception as they are processed top down.)

Custom Exception

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;

namespace Business.Exceptions
{
public class CoordinateNotFoundException : Exception
{
public CoordinateNotFoundException()
{
}

public CoordinateNotFoundException(string message)
: base(message)
{
}

public CoordinateNotFoundException(string message, Exception inner)
: base(message, inner)
{
}
}
}

Consumption

1
2
3
4
private void ThrowCoordinateNotFoundException(string messagePart) 
{
throw new CoordinateNotFoundException($"CoordinatePartsModel {messagePart} is required.");
}

Handling Exceptions

1
2
3
4
5
6
7
8
9
10
11
12
try
{
// do the bad thing
}
catch (CoordinateNotFoundException exc)
{
// handle CoordinateNotFoundException
}
catch (Exception ex)
{
// Handle all other general exceptions
}

References