basel elazaly
basel elazaly

Reputation: 31

unhandled exception in flutter

the error has been caught but why these errors

onPressed: () {
            getName().then((value){
              print(value);
              print('The Last');
              throw('000');

            }).catchError((error){
              print('error (${error.toString()}) has been caught');
            });
        },

this is function

Future<String> getName() async
  {
    return 'Basel Elazaly';
  }
}

and these are output:

Unhandled Exception: Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type

Upvotes: 1

Views: 2002

Answers (3)

Karan Mehta
Karan Mehta

Reputation: 1541

Try this :

            onPressed: () {
              print(getName());
              print('The Last');
              throw('000');            
            },

Function

String getName()
  {
    return 'Basel Elazaly';
  }

It should work properly.

Upvotes: -1

nvoigt
nvoigt

Reputation: 77354

Just program for this century, using async/await instead of .then(). It will get a lot easier:

onPressed: () async {
       try {
         final value = await getName();
         print(value);
         print('The Last');
         throw('000');
        }
        catch(error){
          print('error (${error.toString()}) has been caught');
        }
    },

Official guidance: https://dart.dev/codelabs/async-await#handling-errors

Upvotes: -1

Kaushik Chandru
Kaushik Chandru

Reputation: 17802

Add a throw in catch error like this

onPressed: () {
            getName().then((value){
              print(value);
              print('The Last');
              throw('000');

            }).catchError((error){
              print('error (${error.toString()}) has been caught');
              throw("some other error");//<--here 
            });
        },

Upvotes: 0

Related Questions