In my Flutter app I can't get the try/catch part to work properly.
Future<void> getTime() async {
try {
Response response = await get(Uri.parse('https://api.api-ninjas.com/v1/worldtime?city=$location'),
// provoke an error
headers: {'Api_Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'},
);
Map data = jsonDecode(response.body);
time = "${data['hour']}h - ${data['minute']}m - ${data['second']}s";
}
catch (e) {
print('caught error: $e');
time = 'could not get time data';
}
}
It looks like the catch section is not reached.
Any idea ?
I guess the issue here is that try-catch blocks do not play well with async operations, in order to be able to catch errors in that context please refer to runZonedGuarded, it will encapsulate all method calls and listen to any exception thrown + handle them in a way just like catch does
so I was trying to see how to handle the possibility of my server being down for whatever reason, and I keep getting HTTPLinkServerException without being able to handle it with a try/catch block.
After seing the answer here try catch on HttpLinkServerException doesn't catch error
I also wrote my own error parser, but still doesn't work, since the exception is being thrown because of the HTTP status code. Any thoughts?
Is there something I'm missing on how to catch errors from async* functions? (I'm sort of new to flutter/dart)
The part of my code that triggers the error is this:
try {
final result = graphQLClient.mutate(
MutationOptions(
document: gql(myMutation),
variables: <String, String>{
"var": val,
},
)
);
} catch(err) {
print(err);
}
Thanks!
I want to catch an exception when the url for VideoPlayer is broken, but try{}catch{} didn't catch this exeption.
VideoPlayer cannot play url : http://migration.com:8080/video/test.mp4
Cannot read file.
My method
public async void Initialize(string url){
errorText.text = string.Empty;
_videoPlayer.url = "http://migration.com:8080/video/test.mp4";
_videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
_videoPlayer.targetTexture = rendererTexture;
_videoPlayer.errorReceived += OnPlayerErrorReceived;
try{
_videoPlayer.Prepare();
while (!_videoPlayer.isPrepared)
await UniTask.Yield();
}
catch{}
}
Has anyone solved this problem
What you see in the console is not the result of an actual Exception that is thrown and could be handled by the try - catch.
Unity rather already internally handled this and only prints a Debug.LogError / Debug.LogException for this
=> There is nothing actually thrown you can catch here.
Given the shortcode example below:
...
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} on Exception catch (_) {
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
I would expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch nor the continuation code fires...
flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
What am I missing here?
Functions can throw anything, even things that aren't an Exception:
void foo() {
throw 42;
}
But the on Exception clause means that you are specifically catching only subclass of Exception.
As such, in the following code:
try {
throw 42;
} on Exception catch (_) {
print('never reached');
}
the on Exception will never be reached.
It is not a syntax error to have on Exception catch as someone else answered. However you need to be aware that the catch will not be triggered unless the error being thrown is of type Exception.
If you want to find out the exact type of the error you are getting, remove on Exception so that all errors are caught, put a breakpoint within the catch and check the type of the error. You can also use code similar to the following, if you want to do something for Exceptions, and something else for errors of all other types:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Use:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
The rule is that exception handling should be from detailed exceptions to general exceptions in order to make the operation to fall in the proper catch block and give you more information about the error, like catch blocks in the following method:
Future<int> updateUserById(int userIdForUpdate, String newName) async {
final db = await database;
try {
int code = await db.update('tbl_user', {'name': newName},
whereArgs: [userIdForUpdate], where: "id = ?");
return code;
}
on DatabaseException catch(de) {
print(de);
return 2;
}
on FormatException catch(fe) {
print(fe);
return 2;
}
on Exception catch(e) {
print(e);
return 2;
}
}
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} catch (_) { . // <-- removing the on Exception clause
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
This works, but what is the rationale behind this? Isn't the type inconsistency an Exception?
As everybody or most of the people said, try to know exactly what error you are getting:
try{
}
catch(err){
print(err.runTimeType);
}
runTimeType will give you the type of data or exception you are getting or to put simple the exception itself.
And then do whatever you want. (Like if you are not getting the exception of what you expected, then try to fix that issue or change the exception.)
Another option is to go with general form.
Using the simple catch which will prompt every time.
The other possible reason for the catch bloc not to fire, as pointed out in this question, is missing brackets when throwing an exception.
Must write throw FormatException() instead of throw FormatException.
I had a issue with try catch but my problem was the API that I send http request, doesn't response of my request so that is why my request doesn't response anything and try catch didn't catch the error. So I suggest you to add timeout to your request so that if your api doesn't response your request after a while you can cancel your request with timeout. Here is an example how to use it;
try {
final response = await http.post(Url).timeout(Duration(seconds: 5));
} catch (error) {
print(error)
}
I have a try-catch statement within a try-catch statement. The inner catch catches the error, but the throw does not cause the error to be caught in the out catch statement. Breifly, my script is formatted similar to:
$ErrorPreference = "Stop"
try
{
getStuffFromDB
putStuffInDB
}
catch
{
write-host ("Error: " + $error[0])
}
function getStuffFromDB
{
try
{
-- database query statement
}
catch
{
throw
}
finally
{
close connection and clean up
}
}
function putStuffInDB
{
try
{
-- database insert statements statement
}
catch
{
throw
}
finally
{
close connection and clean up
}
}
When I ran the script there were no errors, but I noticed the SQL Server database that I was attempting to populate was missing data. When I re-ran the script in debug, the function 'putStuffInDB' had an error that was caught in the catch block. But when I stepped the message did not get 'thrown' to the outer catch block, but processed the finally block and terminated.
I am obviously missing something that I am not seeing. I have used the construct in C# in the past and never had issues with errors being 'passed' to the outer catch block.
I am not seeing that behavior. I ran the following in PowerShell ISE and it produces the expected results. Is it possible that the errors in the database were not in fact thrown as exceptions? I believe in SQL Server for example, certain errors under a given error level are not thrown as exceptions back to the ADO.NET provider.
$ErrorActionPreference = 'Stop'
function Throw1 {
try {
Write-Host "Throw1.Try"
throw "Error from Throw1"
}
catch {
Write-Host "Throw1.Catch"
throw
}
finally {
Write-Host "Throw1.Finally"
}
}
function Throw2 {
try {
Write-Host "Throw2.Try"
throw "Error from Throw2"
}
catch {
Write-Host "Throw2.Catch"
throw
}
finally {
Write-Host "Throw2.Finally"
}
}
function Test {
try {
Throw1
Throw2
}
catch {
Write-Host $error[0]
}
}
Test
Produces the following:
Throw1.Try
Throw1.Catch
Throw1.Finally
Error from Throw1
The variable you want to set is $ErrorActionPreference, not $ErrorPreference.
(Josh did set the right variable.)
I realized that the problem was of my own doing. In the POSH functions to create the SQLServer entries I returned the primary key of the data set created. The design of the functions was such that the function would return the primary key. The design mistake was that I put a return statement in the finally block which superceded the throw back to the outer catch. I have changed the design removing the return statement. The try/catch now works correctly.