Let's think about this for a second
By the end of Part 2, all the CRUD operations in the Contact Book work fine — but if the user types invalid input (an empty name, a wrong menu choice), the app can still crash. Here's where we put the exception handling (try/catch) concept from the Advanced chapter into real practice, making the app robust. We'll also use LINQ's OrderBy() to sort the contacts list by name so it displays more cleanly. Once this part is done, the Contact Book project is complete end-to-end — concepts from all three chapters (Basic, Intermediate, and Advanced) have come together in one single project.
Let's build it
Write a custom exception class InvalidContactException that inherits from Exception. In the AddContact() method, throw InvalidContactException whenever Name or Phone is empty. In the Add branch of the Main() method, catch this exception with try/catch and display the error message on the console. Update the ShowAll() method to use LINQ's OrderBy(c => c.Name) so contacts are sorted alphabetically by name. Finally, polish up the output format with Console.WriteLine() calls, adding a header and separator line to make it look nicer.
Code Example
class InvalidContactException : Exception
{
public InvalidContactException(string message) : base(message) { }
}
class ContactManager
{
private List<Contact> contacts = new List<Contact>();
public void AddContact(Contact c)
{
if (string.IsNullOrWhiteSpace(c.Name) || string.IsNullOrWhiteSpace(c.Phone))
{
throw new InvalidContactException("Name and Phone are required.");
}
contacts.Add(c);
}
public void ShowAll()
{
Console.WriteLine("---- Contact List (sorted) ----");
foreach (Contact c in contacts.OrderBy(c => c.Name))
{
Console.WriteLine($"{c.Name,-15} | {c.Phone,-12} | {c.Email}");
}
Console.WriteLine("--------------------------------");
}
}
// Main() ရဲ့ Add branch ထဲမှာ
// try
// {
// manager.AddContact(new Contact { Name = name, Phone = phone, Email = email });
// Console.WriteLine("Contact added successfully.");
// }
// catch (InvalidContactException ex)
// {
// Console.WriteLine("Error: " + ex.Message);
// }You'll end up with a fully polished Contact Book app: trying to add a contact with an empty name or phone number shows an error message instead of crashing the app, and the contact list displays neatly sorted in alphabetical order by name.5-Minute Challenge
Try validating the phone number format with a regex or a simple length check, and throw InvalidContactException again when the format is wrong.
A Quick Heads-Up
Don't just catch an exception and let it fail silently without showing a message — always tell the user what went wrong.