Throwing an Exception
Part of the Logic & Flow section of Coddy's Dart journey — lesson 42 of 65.
Sometimes you need to create your own error conditions in your code. The throw keyword allows you to manually trigger an exception when your program encounters a situation that shouldn't be allowed to continue.
When you throw an exception, you're essentially saying "stop everything - something is wrong here." This is useful for validating input or enforcing rules in your functions. You can throw a simple string message or create more specific exception types.
void checkAge(int age) {
if (age < 0) {
throw "Age cannot be negative!";
}
print("Age is valid: $age");
}In this example, if someone tries to pass a negative age, the function immediately throws an exception with a descriptive message. This prevents the rest of the function from running with invalid data, making your code more reliable and easier to debug.
Throwing exceptions is particularly valuable in functions that need to validate their inputs before proceeding with important operations.
Challenge
EasyCreate a program that validates user account information by implementing custom validation functions that throw exceptions when invalid data is detected. Your program should check multiple account fields and throw specific error messages for different validation failures.
- Read a string input representing the username
- Read a string input representing the email address
- Read a string input representing the age as a string
- Read a string input representing the password
- Create a function called
validateUsernamethat checks if the username is valid: - If the username is empty or has fewer than 3 characters, throw the exception:
"Username must be at least 3 characters long" - If the username contains spaces, throw the exception:
"Username cannot contain spaces" - If validation passes, print:
"Username validation passed" - Create a function called
validateEmailthat checks if the email is valid: - If the email doesn't contain the
@symbol, throw the exception:"Email must contain @ symbol" - If the email doesn't contain a dot
.after the@symbol, throw the exception:"Email must contain a valid domain" - If validation passes, print:
"Email validation passed" - Create a function called
validateAgethat checks if the age is valid: - Convert the age string to an integer using
int.parse() - If the age is less than 13, throw the exception:
"Age must be at least 13 years old" - If the age is greater than 120, throw the exception:
"Age must be realistic (under 120)" - If validation passes, print:
"Age validation passed" - Create a function called
validatePasswordthat checks if the password is valid: - If the password is shorter than 8 characters, throw the exception:
"Password must be at least 8 characters long" - If validation passes, print:
"Password validation passed" - Call each validation function in sequence and handle any exceptions that occur
- Display the results in the exact format shown below
For example, if the inputs are "john", "john@email.com", "25", "password123", your program should output:
Account Validation System
=========================
Validating username: john
Username validation passed
Validating email: john@email.com
Email validation passed
Validating age: 25
Age validation passed
Validating password: password123
Password validation passed
=========================
All validations passed successfully!
Account created for user: johnIf the inputs are "jo", "john@email.com", "25", "password123", your program should output:
Account Validation System
=========================
Validating username: jo
Validation Error: Username must be at least 3 characters long
Account creation failed due to validation errorsIf the inputs are "john doe", "johnemail.com", "12", "pass", your program should output:
Account Validation System
=========================
Validating username: john doe
Validation Error: Username cannot contain spaces
Account creation failed due to validation errorsYour program must call each validation function in the exact order: username, email, age, then password. Stop validation and display the error message as soon as any validation fails. Use the throw keyword to manually trigger exceptions with the specific error messages shown above. Each validation function should check its respective field and throw an exception if the validation fails, or print a success message if it passes.
Cheat sheet
The throw keyword allows you to manually trigger exceptions when your program encounters invalid conditions:
void checkAge(int age) {
if (age < 0) {
throw "Age cannot be negative!";
}
print("Age is valid: $age");
}When you throw an exception, the program stops execution at that point. This is useful for validating input and enforcing rules in functions, making your code more reliable and easier to debug.
You can throw simple string messages or create more specific exception types. Throwing exceptions is particularly valuable in validation functions that need to check inputs before proceeding with important operations.
Try it yourself
import 'dart:io';
void main() {
// Read input
String? username = stdin.readLineSync();
String? email = stdin.readLineSync();
String? age = stdin.readLineSync();
String? password = stdin.readLineSync();
print("Account Validation System");
print("=========================");
try {
// TODO: Create validateUsername function and call it here
print("Validating username: $username");
// TODO: Create validateEmail function and call it here
print("Validating email: $email");
// TODO: Create validateAge function and call it here
print("Validating age: $age");
// TODO: Create validatePassword function and call it here
print("Validating password: $password");
// TODO: If all validations pass, print success messages
print("=========================");
print("All validations passed successfully!");
print("Account created for user: $username");
} catch (e) {
// TODO: Handle exceptions and print error message
print("Validation Error: $e");
print("Account creation failed due to validation errors");
}
}
// TODO: Write your validation functions hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List6Basic Error Handling
What are Exceptions?The 'try-catch' BlockCatching Exceptions with 'on'The 'finally' BlockThrowing an ExceptionRecap - Safe Division