Catch an 'as' typecast exception in flutter

Viewed 2615

how can i catch an 'as' typecast exception in flutter. For example this causes an expection as the cast wasn't successful.

final success = mapJson['success'] as String;

In Swift we can use a guard let or an if let statement. Is there something similar for flutter/dart?

4 Answers

Extending the Answer of @Christopher you can even catch specific exceptions using the on block and execute exception specific code:

try {

// ...

 } on SomeException catch(e) {

//Handle exception of type SomeException
  print(e)

} catch(e) {

 //Handle all other exceptions
 print(e)

} finally {

  // code that should always execute; irrespective of the exception 
 }

You can use a try-catch block to catch all exceptions in nearly any situation. You can read more about them here and from many other places online.

Example usage:

void main() {
  int x = 3;
  var posVar;

  try{
    posVar = x as String;
  }
  catch(e) {
    print(e);
  }
  print(posVar);
}

This print outs

TypeError: 3: type 'JSInt' is not a subtype of type 'String'
null

on DartPad and will be different in a real environment. The code in the try block throws an exception that is caught and can be handled in the catch block.

The Swift guard-let and if-let are used to avoid null values (nil in Swift) and either assign the non-null value to a variable, or execute the else branch (which must contain a control-flow operation in the guard case).

Dart has other patterns for doing the same thing, based on type promotion. Here I'd do:

final success = mapJson['success'];
if (success is String) {
 ... success has type `String` here!
}

With the (at time of writing yet upcoming) Null Safety feature's improved type promotion, you can even write:

final success = mapJson['success'];
if (success is! String) return; //  or throw or another control flow operation.
... success has type `String` here!

You should not make the code throw and then catch the error (it's not an Exception, it's an Error, and you should not catch and handle errors). The "don't use try/catch for control flow" rule from other languages also applies to Dart. Instead do a test before the cast, and most likely you won't need the cast because the type check promotes.

Make use of Null-aware operator to avoid unwanted Null and crash. this is short an alternative to try catch (which is more powerful).

Null-aware operator works like guard let or if let in swift.

enter image description here

?? Use ?? when you want to evaluate and return an expression IFF another expression resolves to null.

exp ?? otherExp

is similar to

((x) => x == null ? otherExp : x)(exp)

??= Use ??= when you want to assign a value to an object IFF that object is null. Otherwise, return the object.

obj ??= value

is similar to

((x) => x == null ? obj = value : x)(obj)

?. Use ?. when you want to call a method/getter on an object IFF that object is not null (otherwise, return null).

obj?.method()

is similar to

((x) => x == null ? null : x.method())(obj)

You can chain ?. calls, for example:

obj?.child?.child?.getter

If obj, or child1, or child2 are null, the entire expression returns null. Otherwise, getter is called and returned.

Ref: http://blog.sethladd.com/2015/07/null-aware-operators-in-dart.html

Also Check Soundness in dart https://dart.dev/guides/language/type-system

Related