'How does throw, Exception, and conditionals work together in Dart?
New to Dart and currently learning about null safety. I've been trying to make a neat simple program with proper null handling while taking input from user (stdin.readLineSync) but I can't seem to get it right.
I've read about nullables and how it can be handled using exceptions. Here, I'm simply trying to take an input from user and store it as an integer.
import 'dart:io';
void main() {
int? nmr;
print('input text to parse:');
String? txt = stdin.readLineSync();
if(txt == null){
throw Exception('field can not be empty!');
} else {
nmr = int.tryParse(txt);
if (nmr == null) {
throw Exception('invalid input!');
} else {
print(nmr);
}
}
}
It run without error, except that when I don't input anything as the txt (txt == null), the console threw the 'invalid input!' instead of the 'field can not be empty' which I was expecting. Where and how did I do wrong? I think perhaps I misunderstood about how the nulls and exceptions work somehow. Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
