C# – Custom Exceptions Programs

InvalidAgeException:

  • Define a method is used to check the person eligible for Vote or Not
  • If the age is not sufficient, throw InvalidAgeException object.
  • We need to handle the exception using try-catch blocks while invoking method.
using System;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Enter Age : ");
		int age = Convert.ToInt32(Console.ReadLine());
		try
		{
			Person.canVote(age);
		}
		catch(InvalidAgeException e)
		{
			Console.WriteLine("Exception : " + e.Message);
		}
	}
}

public class Person
{
	public static void canVote(int age)
	{
		if(age>=18)
		{
			Console.WriteLine("Can vote");
		}
		else
		{
			InvalidAgeException err = new InvalidAgeException("Invalid Age");
			throw err;
		}
	}
}

public class InvalidAgeException : Exception
{
	public InvalidAgeException(string name): base(name)
	{
	}
}

LowBalanceException:

  • Define Account class with initial balance.
  • Define withdraw method.
  • Raise exception if the sufficient amount is not present while withdrawing from account.
using System;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Enter balance in account : ");
		int bal = Convert.ToInt32(Console.ReadLine());
		
		Account acc = new Account(bal);
		Console.WriteLine("Balance is : " + acc.GetBalance());
		
		Console.WriteLine("Enter withdraw amount : ");
		int amt = Convert.ToInt32(Console.ReadLine());
		try
		{
			acc.withdraw(amt);
		}
		catch(LowBalanceException e)
		{
			Console.WriteLine("Exception : " + e.Message);
		}
		Console.WriteLine("Balance is : " + acc.GetBalance());
	}
}

public class Account
{
	private int balance;
	public Account(int balance)
	{
		this.balance = balance;
	}
	public int GetBalance()
	{
		return this.balance;
	}
	public void withdraw(int amt)
	{
		if(amt <= this.balance)
		{
			Console.WriteLine("Collect cash");
			this.balance = this.balance - amt;
		}
		else
		{
			LowBalanceException err = new LowBalanceException("Invalid Age");
			throw err;
		}
	}
}

public class LowBalanceException : Exception
{
	public LowBalanceException(string name): base(name)
	{
	}
}
Scroll to Top