Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create 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.

  1. Read a string input representing the username
  2. Read a string input representing the email address
  3. Read a string input representing the age as a string
  4. Read a string input representing the password
  5. Create a function called validateUsername that 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"
  6. Create a function called validateEmail that 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"
  7. Create a function called validateAge that 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"
  8. Create a function called validatePassword that 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"
  9. Call each validation function in sequence and handle any exceptions that occur
  10. 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: john

If 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 errors

If 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 errors

Your 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 here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow