Catch an 'as' typecast exception in flutter
Solution 1
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.
Solution 2
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
}
Solution 3
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.
Solution 4
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.
?? 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
SwiftiSwift
Updated on December 22, 2022Comments
-
SwiftiSwift over 1 year
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 anif let
statement. Is there something similar for flutter/dart?-
Payam Asefi almost 4 yearsDo you want to show another value if the default value is null? If thats the case you can use something like this:
mapJson['success'] as String ?? " ";
-
Christopher Moore almost 4 years@P4yam This doesn't solve the OP's problem because there will still be an uncaught exception.
-
Payam Asefi almost 4 years@ChristopherMoore Yes thats actually why I posted this comment. I'm not an ios developer but as I know
if let
statement does something like??
cast -
SwiftiSwift almost 4 years@P4yam no, i want to return the function when the casting fails or throw an error that i can catch. But the users below posted it already. I hope there's a shorter version of it
-
-
SwiftiSwift almost 4 yearsThank you. Isn't there a much shorter solution?
-
SwiftiSwift almost 4 yearsThank you. Isn't there a much shorter solution?
-
Christopher Moore almost 4 yearsAFAIK this is the only way of catching exceptions in dart.