In my application I want to take image with camera, and I'm using image_picker
library for that.
Here is my code:
import 'dart:io';
import 'package:image_picker/image_picker.dart';
Future<File> getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
return image;
}
It works fine, but if camera is not available for some reason, then it will crash the application. So, I think we can avoid that by using it inside try/catch
(please correct me if I'm wrong).
I added try/catch
, and here is the updated code:
try {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
} catch (e) {
print(e);
}
return image;
My IDE throws error, variable image
is not defined.
Questions:
try/catch
properly in this case?try/catch
is the approach for these kind of issues?My IDE throws error, variable image is not defined.
Try to slove this issue first.
Change your code:
try {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
} catch (e) {
print(e);
}
return image;
to
var image;
try {
image = await ImagePicker.pickImage(source: ImageSource.camera);
} catch (e) {
print(e);
}
return image;
Q1. How do I use try/catch properly in this case?
A1. I think you did It right.
-
Q2. Does try/catch is the approach for these kind of issues?
A2. Yes, absolutely. You might want to check the exceptions on image_picker
-
Q3. Is there any other error/exception, I should care about?
A3. This is hard to know, you should look at source code, or just handle the exception you interested, and let others be an Alert (AlertDialog
, Snackbar
...etc).
As with most C-like languages, variables declared within a scope are available only within that scope. In other words, if you declare a variable within a {
... }
block, it cannot be directly referenced outside of that block. If you need to use a variable in an outer block, then you will need to move its declaration out.
- How do I use
try
/catch
properly in this case?
You should avoid catch (e)
as that will catch all types of exceptions, including logical errors (AssertionError
. ArgumentError
, etc.).
The usual recommendation is to avoid catching exceptions that derive from Error
. (Typically this means catching only runtime errors, which should be exceptions that derive from Exception
instead. In practice there is code that does not does not follow this distinction, and in some cases there isn't a clear line between what should be considered a logical error and what should be considered a runtime error.)
- Does
try
/catch
is the approach for these kind of issues?
If no mechanism is provided to check in advance whether an operation will succeed ("look before you leap"), then you don't have any choice but to try it and to check for failure ("easier to ask for forgiveness than permission").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With