Sobes.tech
Junior — Middle

Can you give an example when you create your own exceptions in code?

sobes.tech AI

Answer from AI

Custom exceptions are created when standard exceptions are insufficient to accurately describe an error in the application's business logic. For example, if you have a banking application, you can define an exception InsufficientFundsException, which will be thrown when attempting to withdraw an amount exceeding the balance.

Example in C#:

public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(string message) : base(message) { }
}

public class BankAccount
{
    public decimal Balance { get; private set; }

    public void Withdraw(decimal amount)
    {
        if (amount > Balance)
            throw new InsufficientFundsException("Insufficient funds in the account.");
        Balance -= amount;
    }
}