Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
0 So in the last lesson, we managed to get our geolocator to work and grab the current position of the 1
user's device to a low accuracy level. 2
So something like two or three blocks kind of range. 3
Now at the moment all that we're doing is using that one method, 4
but we have to realize that there's a lot of cases where this might fail right? 5
So for example if the user didn't give us permission to get their current position, when that pop up 6
came up to ask them for location permission they said no. 7
There's also other problems such as if the use'rs in a tunnel and it's physically impossible to actually 8
get any signal from them to get their GPS address. 9
So in order to be able to handle all of these errors that might arise we have to learn about how Dart 10
handles exceptions. 11
Now we know that when you write bad code, then our code usually won't even compile. Before it gets to 12
run the errors get caught, they get underlined and it'll tell you there's a problem with your code don't 13
run it and it'll refuse to run the app. 14
So for example let's say that we created a string called myString and we set it equaled this string, 15
so inside single quotes the number 15. 16
Now at this stage if I tried to add the number five to my string, so I'll write myString plus five. 17
Let's try and do some basic arithmetic with strings and numbers. 18
Well it tells me it can't do that because this is an integer and this is a string. 19
It doesn't know how to combine different types. 20
This is what we would call a compile time error. 21
These errors are really easy for us developers to catch because our app won't even run and we'll definitely 22
be alerted to them. 23
When something unexpected happens while your code is running well, then what happens? For example 24
in Dart there is a method that is called parse and it allows us to take a string and turn it into a double. 25
So for example we can say double.parse and we can provide a string. 26
So I'm going to provide myString as a double. 27
And then this method will turn that string into a double. 28
So 15 as a string becomes 15 as a number. 29
Now let's store that inside a double type variable and we'll call it myStringAsADouble. 30
We'll set it to equal the output of that method. 31
Now we don't have any errors anymore because the job of this method is turn strings into doubles. 32
And in this case, it's pretty easy. 15 as a string if you remove the single quotes, it becomes a double 33
right? 34
So we can even print this out and we can say myStringAsADouble 35
and we can even add five to it if we wanted to. 36
Now at this stage there's no compile time errors because all the data types are what they should be. 37
And if I hit run, you can see that my string 15 gets turned into a double 15 and then it gets five added 38
to it. 39
And that gets printed in the console. 40
So that's pretty good. 41
But what if I wrote some bad code and I gave it something that it can't actually work on? 42
So if I turn myString into 'abc' and I try to get my code to pass that string abc into a double and try 43
to add five to it. 44
Well what happens in this case? 45
Now notice how we're not getting any compile time errors because all that it checks at compile time 46
is that for the inputs that you're putting in, it matches the data type that it expects, 47
so in this case parse requires a string data type as the source, 48
and that's exactly what we're providing. We're providing a string. 49
Now it doesn't know that we're actually tricking it and trying to give it an actual piece of text to 50
try and turn into a number, a job that a human can't even do. If you give me the words abc and told me, 51
'give that back to me as a number', I wouldn't really know what to do either let alone our computer. 52
But notice how this error is going to happen in the future while our app is running. 53
So this is fine. 54
And this is fine. 55
But at the point when it tries to turn a piece of text, abc, into a number, that's where it's going to 56
trip over and fail. 57
So that's going to happen while the app is running or during runtime. 58
So now if I hit run and start off our runtime, you can see I get an exception that's not been caught. 59
So an uncaught exception and it tells me that abc is not actually a double. 60
You can't turn this into a double or into a number. 61
So this method here parse, it's really relying on you being truthful and being good and always giving it 62
a string that can be turned into a number. 63
But as our code grows and as it gets larger, we don't always know what's being passed around. And we might 64
make an honest mistake just like this. 65
So we don't want our app to crash. But instead we want to make sure that we catch our exception. So in 66
answer to that question, when something unexpected happens while your code is running, what should you do? 67
Well in that moment the program is going to throw out an error and it's your job as the programmer to 68
catch that error and handle it. And to do that we can use try and catch. 69
So we're going to take the parts that we know can fail, 70
so for example this part, and we're going to wrap it inside a try block. So we're going to say, 'try to 71
do this'. But if it fails, then we're going to catch the error inside a catch block. 72
So we're going to provide catch and then we're going to give the exception a name, so you call it exception 73
exception, or in most cases you're going to see this written as e short for exception or error. 74
Now inside this catch block we can actually print out the error. And now when I run my code, you'll see 75
that instead of having a uncaught exception, my exception is now caught and it's now printed into the 76
console. 77
At this point some of you might ask, well what's the difference? 78
Same thing happened right? 79
You had an exception and we know what the exception is when we look in the console, 80
what's the point of adding in that try and catch block? Well, 81
the difference is that if an exception occurs and it's not caught inside a catch block, your code will 82
crash. 83
That means your app will crash and your users will see a black screen or your app will exit. 84
But if you do catch it, well you can respond to it and you can plan ahead. 85
So let's see try and catch in action in our Flutter app. 86
Let me quickly show you an example of how unhandled exceptions lead to a crash. 87
Also let me show you how we could recover from an exception and avoid a crash. 88
I'm going to delete everything that's currently inside my build method for the loading screen. And instead 89
I'm going to return something based on a result, and that result is going to be based off a string called 90
myMargin and it's going to be equal to 15, 91
but as a string. And then I'm going to return a scaffold widget which is going to contain a body parameter 92
and for the body of the scaffold, it's going to be a container that has a color of red and it's also 93
going to have a margin property which is of course created using the EdgeInsets. 94
And I'm going to have a margin on all four sides. 95
Now the value that I'm going to use in here is going to be a double because it expects a double. 96
And I'm going to use that parse method to turn my string, myMargin, into a double so that it can be used 97
as the margin for my container. 98
So now at this stage if I go ahead and run my app, let's see what happens. 99
You can see that once the app is up and running, 100
I have this red container and it's been given 15 pixels ofmargin from all four edges. 101
based on this line of code. 102
Now let's break our code. 103
Let's change this margin to an actual piece of text which we know can't be parsed into a double. 104
Now at this stage as soon as I hit save, you'll see that hot reload happens and this line of code gets 105
carried out and my app crashes right? 106
I see nothing onscreen and I see a lot of errors inside my console. 107
Now had I been prepared for this and I knew that some at some stage maybe it was possible that something that 108
couldn't be passed into a double, was put into here as the input. 109
Well then I could've caught that in an exception. 110
So let's move this line of code out and let's create a double which is going to be called myMargin 111
AsADouble. 112
And we're going to set it equal to double.parse(myMargin) 113
Now we know that this is the offending line of code, 114
so this is something that could break. Well 115
so in this case we're going to say try and do this, but if you fail then we're going to do something 116
else. 117
So we're going to catch the exception and we're going to print the exception. Also we're going to 118
provide an alternative widget to render. 119
So let me copy that and paste it in here. 120
It's also going to be a scaffold and it's going to have a container. 121
And in this case, myMargin is simply going to have a default value of 30. So in this case we're saying 122
try and turn this margin into a double. 123
And if you can, then use myMarginasADouble inside this container that you're going to render but 124
if there were any errors with this, then try and catch that inside a catch block and not only print the 125
exception into the console but also provide an alternative, so provide a different container. 126
Now at this stage if I hit save and let's reload our app, you can see that even though this code is 127
still failing and I'm getting my exception printed into my console, 'Invalid double' That's abc. I'm getting 128
an alternative reality being rendered on screen. 129
Now if we look at our code, it's actually doing something really simple. 130
It's simply providing a default value for our margin when parsing myMarginasADouble has an error 131
and myMargin doesn't actually have a value. 132
Now we can make this much simpler using another construct from Dart that's really useful. Instead of creating 133
two alternative scaffolds, let's take this out of all try catch block and keep it really simple. 134
So all it does is it tries to turn our margin into a double and then if there were any errors, it'll 135
catch it. 136
And our build method is simply going to try and return a scaffold 137
using this myMargin as double. 138
So let's move that out of the try block, up here, and it's going to start out with no value. 139
So it's going to start out with null, but it's gonna try and turn myMargin into myMarginasADouble 140
by parsing this value myMargin. 141
Now if there were any exceptions it's going to print the exception but we're still going to return a 142
widget nonetheless. 143
Now in this case it's going to use myMarginAsADouble. But if we run our code right now, margin as 144
a double tries to be turned into a double 145
but because it's a piece of text, this fails and the catch block gets triggered. 146
Now in this case we can either say if there were any errors turning into a double, let's change myMargin 147
AsADouble into a default value, let's say a 30 right? Now in this case, you can see that the margin of 148
30 gets given to our red container and it's using it from here because we know that we definitely can't 149
convert abc into 30 150
right? 151
So it's actually the catch block that's being triggered and we see the exception in the console as well. 152
But there's actually a much easier way of doing this checking to see if a particular variable is equal 153
to null, 154
in that case providing a alternative value. 155
And we can do it right here in line with our margin property. 156
So instead of trying to provide a value here, we can say myMarginAsADouble 157
and then we add two question marks. 158
And what this syntax says is that if this has a value i.e. it's not null, then use it. 159
But if it is null, then use my alternative instead. 160
So use 30 in its place. 161
And this line of code works exactly the same as before. 162
You can see that the margin of 30 is being applied here because myMarginAsADouble at the moment is 163
equal to null. 164
And we're also getting some exceptions thrown which we could handle in our catch block. 165
Now let's say that I change this to an actual number that can be parsed so that this line of code actually 166
succeeds. 167
Then when I run the code then you'll see that the margin changes to 15 instead. It's preferentially using 168
this value but if it actually is equal to null, 169
then this operator makes sure that we have a default value in its place so that we don't end up having 170
a blank screen or problems rendering our margins. So 171
in this lesson, we saw the try catch block where we can enclose a line of code that might fail and might 172
throw an error, inside a try block. And if it does throw the error then we'll catch it inside our catch 173
block. And we can either handle the exception by printing it or by putting it onto the screen to alert 174
the user or we can provide an alternative reality in the catch block. 175
We also saw the null aware operator and in this case what happens is that we have some sort of variable 176
that we know could be null at some point, it might not contain a value. 177
So in that case we add two question marks saying that if in the future when we try to use this variable 178
and it's equal to null, then use this default value instead. 179
But if it does in fact have a value then use that value, so that we're aware that a variable can be null, 180
and if it is, we provide an alternative. 181
So let's apply what we've just learned to our code inside getLocation. So we know that this is the line 182
that probably could fail in certain cases, say if we didn't get permission to get the location or if 183
the user is unreachable and we can't figure out their GPS and even the device doesn't know their GPS 184
address. 185
So let's wrap this line of code. 186
So Android Studio is putting it onto two lines just to make it easier to read. 187
But this is in fact all one line of code and we're going to wrap it inside a try block. 188
So I'm going to add the try keyword, add a set of parentheses and then I'm going to wrap everything that 189
depends on that position inside the try block. And then I'm going to follow that with a catch block and 190
inside a set of parentheses, I'm going to put the exception or simply e for short. And inside the catch 191
block we can print the error or exception if it does occur, or if we're being more sophisticated we can 192
actually try and figure out what the error is and decide on an alternative route based on that. 193
So as Benjamin Franklin says by failing to prepare, you're preparing to fail. 194
So we have to make sure that we always prepare for the worst case scenario when something doesn't work 195
or something might throw an exception 196
and we have to try and catch it so that we can handle it or deal with it or provide an alternative path. 197
Now let's talk about the last piece of the puzzle of the try catch block, namely what actually triggers 198
an exception? 199
Where do these exceptions actually get thrown from? The key to understanding this is the throw keyword. 200
A method can throw an exception 201
and by throwing an exception, we can handle the exception in a try catch block. 202
Let me show you how to create a method that throws an exception. 203
So here I'm going to create a new method called somethingThatExpectsLessThan10. 204
So this is really long. 205
And it needs to take an input which is an integer and we'll call that 206
n. Now inside the body of the method, we have to do something with this integer. 207
And but we should expect that in all circumstances, n should always be less than 10. And if n was greater 208
than 10, then something terrible has happened. 209
And in that case we have to throw an exception. 210
We can't work with something larger than 10. 211
So in this case, we would use the through keyword to throw out an error and our exception is going to 212
read, 'n is greater than 10, n should always be less than 10'. 213
So here's our exception. 214
And now let's say inside our getLocation instead of trying to print the position and get the position 215
from our geolocator, we instead use our method somethingThatExpectsLessThan10 and for n, we're going 216
to put in 12 which clearly is going to violate our rules and it's not going to work. 217
So now if we hit run and we check out the console 218
then you can see that we get, 'n is greater than 10, n should always be less than 10' thrown as the 219
exception. 220
But if we didn't handle the exception if we didn't have this try and catch block and we tried to run 221
this code that throws an exception under certain conditions, then our app will actually crash. So let's 222
get rid of that method here and here. 223
And let's bring our code back with the try catch block. Now going back to our getCurrentPosition method, 224
let me show you where this method actually throws an exception. For this, 225
we'll need to peek inside the geo location package. 226
If we take this method and we hold down COMMAND and we click on it, it takes us to where it was declared 227
or where it was created. And you can see here in this method that's created from the geolocator library, 228
you can see that it checks to see if permission is permission status granted, so the user actually allowed 229
you to access their position, 230
and then we try and get the location. But if they didn't let you have their permission, then it would handle 231
the invalid permissions. 232
And here we see how the exceptions are thrown. 233
There are two cases when an exception is thrown by our geo location package, permission denied and permission 234
disabled. 235
This is the throw keyword which triggers the exception inaction. 236
This is why we wrapped the getCurrentPosition method in a try catch block.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.