Creating Exceptions in C#

As we saw earlier, when an error occurs in our system, we encounter what is defined as an exception.

In this post, we will see an extension of that post. Here, we will create our own exceptions.

The main benefit of having custom exceptions is that they allow us to control our code, and, more importantly, they are mainly used for monitoring our website.

For our example, let's imagine we have an invoice system, and a user tries to access an invoice that does not belong to them.

 

1 - Create a Custom Exception

To create a custom exception, we only need to create a class that implements the Exception object and define a constructor, as shown in the example.

public class FacturaDiferenteClienteException : Exception
{
    public FacturaDiferenteClienteException(string message) : base(message)
    {
        Console.WriteLine(message);
        Util.EnviarEmailAlerta("Intento de hackeo", message);
    }
}

To simulate a system, I created a Util class that contains a EnviarEmailAlerta method, since in this particular example it's either a serious bug or a hacking attempt.

 

 

2 - Use a Custom Exception

To use the exception we just created, we need to instantiate it manually. For this, and to speed up the example, I created a class called Repository to which we pass two IDs, and it simply returns true or false. (the complete code is on GitHub, link below)

Let's get to it: we make the call, and if it returns false, it means the client and the owner of the invoice do not match. In that case, we throw our exception, as shown in the following code:

if(!repo.ClienteYFacturaDuenoSonElMismo(clienteId, facturaId))
{
    throw new FacturaDiferenteClienteException($"El cliente {clienteId} esta intentando acceder a la factura {facturaId} que no le corresponde.");
}

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café