Home > Mobile >  try/catch bloc doesn't work in dart/flutter
try/catch bloc doesn't work in dart/flutter

Time:12-08

I have an exception :

class WrongHourException implements Exception {}

and I have a function that check many things such as checking hour :

void confrimSchedule() async {
  late double start;
  late double end;
  late double period;

  //check the validation of hours
  if (int.parse(startHour) > 24 || int.parse(startHour) < 0) {
    throw WrongHourException(); // line 26 scheduel_functions
  } else if (int.parse(endHour) > 24 || int.parse(endHour) < 0) {
    throw WrongHourException();
  } else if (int.parse(endHour) < int.parse(startHour)) {
    throw WrongHourException();
  }

}

this is where I want to use try/catch :

try {
        confrimSchedule( // line 161 scheduel_bloc.dart
          startHour: event.startHour,
          startMinute: event.startMinute,
          endHour: event.endHour,
          endMinute: event.endMinute,
          periodMinute: event.period,
          day: event.day,
        );
        emit(ScheduelStateDayView(
          day: event.day,
          isLoading: false,
          isScheduelLoading: false,
        ));
      } on Exception catch (e) {
        emit(ScheduelStateDayView(
          day: event.day,
          isLoading: false,
          isScheduelLoading: false,
          exception: e,
        ));
      }

but I got an Error that telling me Unhandled Exception : Instance of 'WrongHourException' why try/catch doesn't working?

this is error image

CodePudding user response:

It seems like the code for confrimSchedule in your question is incomplete, because it is marked as async without actually doing any async work. My guess is that you are not awaiting the confrimSchedule call and thus the exception handling code is not used.

CodePudding user response:

When you call

confrimSchedule( // line 161 scheduel_bloc.dart
          startHour: event.startHour,
          startMinute: event.startMinute,
          endHour: event.endHour,
          endMinute: event.endMinute,
          periodMinute: event.period,
          day: event.day,
        );

You are not waiting for the result. Change that line for

await confrimSchedule( // line 161 scheduel_bloc.dart
          startHour: event.startHour,
          startMinute: event.startMinute,
          endHour: event.endHour,
          endMinute: event.endMinute,
          periodMinute: event.period,
          day: event.day,
        );

or

confrimSchedule( // line 161 scheduel_bloc.dart
          startHour: event.startHour,
          startMinute: event.startMinute,
          endHour: event.endHour,
          endMinute: event.endMinute,
          periodMinute: event.period,
          day: event.day,
        ).then((_){
//emit here
});
  • Related