Home > database >  how to use the object inside catch
how to use the object inside catch

Time:08-30

How to I convert the object inside catch?

class Sample {
  final String? errorCode;
  Sample({this.errorCode});
}

void main() {
  var sample = Sample(errorCode: 'sample');
  try {
    throw sample;
  } catch(err) {
    print(err); // I would like to get the errorCode e.g. err.errorcode
  }
}

CodePudding user response:

Either make sure to only catch a Sample, then err will have that type:

} on Sample catch (error) {
  print(error.errorCode);
}

or check/cast inside the catch block:

} catch (error) {
  if (error is Sample) print(error.errorCode);
  print((error as Sample).errorCode);
}

The first approach is safer if you only expect to catch a Sample. The is-check can be used if you want to catch other things too, but treat Sample specially.

The as should not be used outside of quick-and-dirty code, because it can throw if you catch something other than a Sample, and you don't want your error handling to throw!

  •  Tags:  
  • dart
  • Related