Home > Net >  I can't handle the error with try-catch block in Dart
I can't handle the error with try-catch block in Dart

Time:06-16

I am learning Dart. I was trying to learn how try-catch works by creating a silly error. But unfortunately, it seems my catch block is not been reached. It's just throwing an unhandled error. Why it's happening? This is the code-

void main(List<String> args) {
  try {
    int x = 44 / 0;
    print(x);
  } catch (e) {
    print('It is an infinity error');
  }
}

CodePudding user response:

Your error are a static compile error from the type system since you are trying to assign a double to a int variable. This types of errors cannot be catch since they will happen before the program are even attempt running.

If you want to do this division but want a int as the result, you can use the ~/ operator:

So this works where the exception are triggered:

void main(List<String> args) {
  try {
    int x = 44 ~/ 0;
    print(x); // <-- not executed
  } catch (e) {
    print('It is an infinity error'); // <-- this is printed
  }
}

You can also assign the result to a double value. This, however, does not work as you expect since double will not fail but instead represent the value as Infinity:

void main(List<String> args) {
  try {
    double x = 44 / 0;
    print(x); // Prints: Infinity
  } catch (e) {
    print('It is an infinity error'); // <-- not executed
  }
}

CodePudding user response:

But my question was how can I activate the catch block? I know it will be an error. But the catch block is not executed It's giving me an unhandled error. I am not trying to fix it My question was how to handle the error & run the catch block.

  •  Tags:  
  • dart
  • Related