flutterdart

Why Dart code with assert() is not throwing error


I have the following code:

void main(List<String> arguments) {
  print('Enter your age: ');
  try {
    int? age = int.tryParse(stdin.readLineSync()!);
    print('Age is $age');
    assert(age != null, 'Age cannot be null');
    print('You are $age years old');
  } catch (e) {
    print('You gave us a bad age');
  }
}

When I run it and I enter the age to be a string like 'nnnnn' (something that does not parse to an int) I am expecting the assert to throw an error, but the output is 'You are null years old'. I am new to Dart and this is making me crazy, most likely I am doing something wrong? Thanks


Solution

  • The reason assert() isn't throwing an error is because asserts are only active in debug mode. If you're running your Dart code in release mode or without enabling asserts, they’ll be ignored.

    To ensure assert() runs, use:

    dart run --enable-asserts main.dart

    Or make sure your IDE is running in debug mode.

    Important Note: assert() is for development-time checks only. For runtime validation (like user input), use if statements or throw exceptions manually:

    if (age == null) {
      throw FormatException('Age cannot be null');
    }