why the assert function was disabled in dart?

僤鯓⒐⒋嵵緔 提交于 2021-01-29 13:36:12

问题


import 'dart:io';
main() {
  print("Enter an even number : ");
  int evenNo = int.parse(stdin.readLineSync());
  assert(evenNo % 2 == 0, 'wrong input');
  print("You have entered : $evenNo");
}

to get this code to work properly I had to run the dart file with '--enable-asserts' tag and before assert function was executed without passing the '--enable-asserts' tag. why was this function disabled ?


回答1:


What is an assertion?

In many languages, including Dart, "assertions" specifically are meant to catch logical errors. (Dart calls these Errors.) These are errors that are due to a programming mistake. These types of errors should never happen. Conceptually, a sufficiently advanced static analyzer could prove that assertions will never fail. In practice, such analysis is difficult, so assertions are verified at runtime as a matter of practicality.

This is in contrast to runtime errors, which are unpredictable errors that occur when the program is actually running. (Dart calls these Exceptions.) Often these types of errors are due to invalid user input, but they also include file system errors and hardware failures, among other things.

Assertions are intended to be used to verify assumptions (or catch faulty ones) when debugging, and programming languages that have assertions typically allow them to be disabled for production (non-debug) code. Since assertions logically should never occur, there is no point in incurring the extra runtime cost of checking them. Since assertions can be disabled, that also should provide additional discouragement against using them improperly.

Dart chose to leave assertions disabled by default, so you must opt-in to using them with --enable-asserts. Some other languages (e.g. C) chose an opt-out system instead. I don't know the rationale for this choice for Dart, but since asserts should be used only for debugging, it makes sense to me that a language like Dart (which often might be interpreted) makes it easier for users to execute code in production mode. In contrast, for compiled languages like C, the onus of enabling or disabling assertions is placed on the developer rather than on the user.

What does this mean for your code?

Your code does not use assert properly: You use it to check runtime input. That instead should be a check that you always perform and that produces a runtime error if it fails:

if (evenNo % 2 != 0) {
  throw FormatException('wrong input');
}


来源:https://stackoverflow.com/questions/61220115/why-the-assert-function-was-disabled-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!