Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Combining Custom Exceptions and Guard Clauses | Custom Exceptions and Guard Clauses
C# Exceptions and Error Handling Practice

bookCombining Custom Exceptions and Guard Clauses

Combining guard clauses with custom exceptions is a powerful way to make your C# code clear, robust, and easy to maintain. Guard clauses act as early checks at the start of a method, immediately throwing an exception if a condition is not met. When you pair these with custom exceptions, you create precise error messages tailored to your application's business rules. This approach not only prevents invalid data from proceeding further into your logic, but also makes debugging much easier, since errors are detected and reported as soon as they occur, with meaningful context.

Program.cs

Program.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142
using System; namespace ConsoleApp { // Custom exception for business rule violations public class AgeRequirementException : Exception { public AgeRequirementException(string message) : base(message) { } } public class UserRegistration { public void RegisterUser(string username, int age) { // Guard clause: user must be at least 18 if (age < 18) { throw new AgeRequirementException($"User '{username}' is too young to register. Must be at least 18."); } Console.WriteLine($"User '{username}' registered successfully."); } } public class Program { public static void Main(string[] args) { var registration = new UserRegistration(); try { registration.RegisterUser("alice", 16); } catch (AgeRequirementException ex) { Console.WriteLine($"Registration failed: {ex.Message}"); } } } }

By using a guard clause at the start of the RegisterUser method, you immediately check the age and throw a custom exception with a clear message if the user is too young. This makes it obvious where and why the registration failed. Custom exceptions like AgeRequirementException give you more control over error handling and provide specific information, making the debugging process much more straightforward. You can quickly pinpoint which business rule was violated and respond accordingly, instead of handling vague or generic errors.

MultipleGuardClauses.cs

MultipleGuardClauses.cs

copy
123456789101112131415161718192021222324252627282930313233
// Not runnable: illustration of multiple guard clauses and custom exceptions namespace ConsoleApp { public class InvalidEmailException : Exception { public InvalidEmailException(string message) : base(message) { } } public class PasswordTooWeakException : Exception { public PasswordTooWeakException(string message) : base(message) { } } public class UserRegistration { public void Register(string email, string password) { if (string.IsNullOrWhiteSpace(email) || !email.Contains("@")) { throw new InvalidEmailException("Email address is invalid."); } if (password.Length < 8) { throw new PasswordTooWeakException("Password must be at least 8 characters long."); } // Proceed with registration } } }

1. Why combine guard clauses with custom exceptions?

2. What is a business rule exception?

question mark

Why combine guard clauses with custom exceptions?

Select the correct answer

question mark

What is a business rule exception?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

bookCombining Custom Exceptions and Guard Clauses

Swipe to show menu

Combining guard clauses with custom exceptions is a powerful way to make your C# code clear, robust, and easy to maintain. Guard clauses act as early checks at the start of a method, immediately throwing an exception if a condition is not met. When you pair these with custom exceptions, you create precise error messages tailored to your application's business rules. This approach not only prevents invalid data from proceeding further into your logic, but also makes debugging much easier, since errors are detected and reported as soon as they occur, with meaningful context.

Program.cs

Program.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142
using System; namespace ConsoleApp { // Custom exception for business rule violations public class AgeRequirementException : Exception { public AgeRequirementException(string message) : base(message) { } } public class UserRegistration { public void RegisterUser(string username, int age) { // Guard clause: user must be at least 18 if (age < 18) { throw new AgeRequirementException($"User '{username}' is too young to register. Must be at least 18."); } Console.WriteLine($"User '{username}' registered successfully."); } } public class Program { public static void Main(string[] args) { var registration = new UserRegistration(); try { registration.RegisterUser("alice", 16); } catch (AgeRequirementException ex) { Console.WriteLine($"Registration failed: {ex.Message}"); } } } }

By using a guard clause at the start of the RegisterUser method, you immediately check the age and throw a custom exception with a clear message if the user is too young. This makes it obvious where and why the registration failed. Custom exceptions like AgeRequirementException give you more control over error handling and provide specific information, making the debugging process much more straightforward. You can quickly pinpoint which business rule was violated and respond accordingly, instead of handling vague or generic errors.

MultipleGuardClauses.cs

MultipleGuardClauses.cs

copy
123456789101112131415161718192021222324252627282930313233
// Not runnable: illustration of multiple guard clauses and custom exceptions namespace ConsoleApp { public class InvalidEmailException : Exception { public InvalidEmailException(string message) : base(message) { } } public class PasswordTooWeakException : Exception { public PasswordTooWeakException(string message) : base(message) { } } public class UserRegistration { public void Register(string email, string password) { if (string.IsNullOrWhiteSpace(email) || !email.Contains("@")) { throw new InvalidEmailException("Email address is invalid."); } if (password.Length < 8) { throw new PasswordTooWeakException("Password must be at least 8 characters long."); } // Proceed with registration } } }

1. Why combine guard clauses with custom exceptions?

2. What is a business rule exception?

question mark

Why combine guard clauses with custom exceptions?

Select the correct answer

question mark

What is a business rule exception?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 5
some-alt