Home > Software engineering >  catchError and "try - catch" is not working (async)
catchError and "try - catch" is not working (async)

Time:02-16

My code is trying to communicate using Socket, but I can't seem to catch the exception.

I've tried these things, but they don't work and I get an exception on the IDE.

Socket socket;
try {
  socket = await Socket.connect(ip, port);
  // Instead of jumping to errorProcess(), the IDE will show an exception here...
} catch(e) {
  errorProcess(e);
}
Socket socket = await Socket.connect(ip, port).catchError((e) {
  errorProcess(e);
  // catchError says we need to return FutureOr<Socket>...
});

How can I catch exceptions?

CodePudding user response:

Try adding SocketException for your try catch statement.

Example Code:

try {} on SocketException catch (e) {
      print(e);
    } catch (e) {
      print(e);
    }
  • Related