Custom Exceptions
A custom exception is an alarm you design yourself for your own special kind of problem. It makes error messages meaningful for your program.
In this page:
Syntax
class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}
throw new CustomException("message");
Custom Exceptions
You can define your own exception type by inheriting from Exception (or a more specific subclass), which lets calling code catch a precise, meaningful error type for your domain.
Custom exceptions usually forward a message to the base constructor. This is standard practice for libraries reporting domain-specific failures.
Note:
Name custom exceptions ending in "Exception", like
InsufficientFundsException.Example: Custom Exceptions
using System;
class InsufficientFundsException : Exception
{
public InsufficientFundsException(string message) : base(message) { }
}
class Account
{
public decimal Balance = 100;
public void Withdraw(decimal amount)
{
if (amount > Balance)
throw new InsufficientFundsException("Not enough funds");
Balance -= amount;
}
}
class Program
{
static void Main(string[] args)
{
Account acc = new Account();
try
{
acc.Withdraw(500);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Not ending the class name with
Exception, which breaks the .NET naming convention. - Forgetting to call the base constructor with the message, so the message is lost.
- Deriving from
ApplicationExceptioninstead ofException, which is not recommended.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: