How to handle errors in functions – Swift for Complete Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] things go wrong all the time whether it's trying through the file and finally it doesn't exist or trying to download some data from the internet only for the network to go down or who knows what now if we don't handle errors like these gracefully our app will just go pop it'll just crash so swift forces us to think about them or at least acknowledge that they exist this takes three steps step one define all the errors that might happen in the code we're writing step two write a function that works as normal but can throw one or more of those errors if a serious problem is found then step three try and run that function and handle any errors that come back now i want to work through a complete example here if the user asks us to check the strength of their password we'll return how good it is okay good excellent whatever but if it's really bad if it's too short or really obvious will flag up a serious fatal error please fix it so step one we want to define the kinds of problems that can occur inside our function so we're going to say is the new enum building on swift's built-in error type this has two cases short and obvious password is too short a password is too obvious those are two errors and honestly it doesn't define anything about what those two mean they mean nothing they just exist there is a possible error called short and a password error called obvious step two is to write a function that will trigger one or more of those errors now where an error is triggered or as you say in swift uh throne we're saying something fatal has gone wrong in the function we cannot continue do not continue as normal don't try and send back a value just immediately terminate and throw up the error to be handled somewhere else in our case we're going to write a function that checks the strength of a password it'll say if it's really bad fewer than five characters for example will throw an error immediately if it's extremely well known we'll throw the obvious error but otherwise return okay good or excellent ratings depending on how the user's strength is here's how it looks in swift first up we'll say funk chess password password string return string but notice that throws keyword before the return type we'll then say for less than five characters it's too short if it's one two three four five the same password i have in my luggage so it's obvious otherwise do various checks shorten a character is okay shorter than 10 it's good otherwise it's excellent let's break that down to smaller bits if a function is able to throw errors we must mark it with throws the throws keyword before the return type we do not specify the kinds of errors that can be thrown we don't say it throws a password error just that it can throw errors now being marked with throws means it can throw errors not that it must throw errors it could happen if things go wrong but it might not it might also work perfectly in fact we hope it does work perfectly right the happy path through this is it's all working great when it comes time to throw errors like in those first two lines of code we say throw followed by one of our errors password error.short or the obvious or whatever this will immediately exit the function it will not return a string you'll not run any further code it'll exit immediately to be handled somewhere else now i've put the if password cat lesson five throw short all on one line just for space reasons on my slide here right ideally you don't write code quite so compressed but there's not a lot of space on one screen if no errors are thrown those first two lines pass nicely we go to the next chunk and work as normal it must return a string we promise to return a string it needs to return a string and that completes the second step of throwing errors we've defined the areas that might happen first step then wrote a function using those errors second step a final step is to run the function and handle any errors that might occur now swift's playgrounds in xcode are pretty lacks about handling errors they're mostly meant for learning but when it comes to writing real swift and swift ui projects they'll complain bitterly they'll make sure you handle errors properly and that means doing three smaller steps first up start a block of code that might throw errors by saying do and open brace then call one or more throwing functions by saying try then have a catch block to handle any errors that come back now in pseudocode not real swift they haven't got this function yet it looks like this do try some risky work catch print handle errors here of course you want to have a some risky work function doing real work but you get the idea we say do all are throwing code try this try that try something else then catch the errors that come back let's try it out in xcode with our real function here's our check password right now i'll say let's string equals one two three four five then we'll do a do we'll say let result equals try check password with that string and then print password rating is result now i've got to catch the errors here i'll just say print there was an error like that i'll press play boom there was an error comes back correctly now what matters here is if the check password function runs successfully it all works correctly it'll return a value back into result and then carry on running the next line of code in the do block which in this case will print it out but if any errors are thrown this whole do block ends it'll jump straight to the catch block here we'll say there was an error now there are a few different parts of this that really deserve more discussion but i want to focus on the most important one which is hear try this must be written before all throwing functions as a signal to yourself and other developers that regular code execution might stop here it might get to here and get no further because an error is thrown and it will jump down to the catch block now when you use try like this you gotta be inside a do block and handle the areas inside the catch blocks in some circumstances a handful of circumstances you can write a different version of try which is try exclamation mark which does not require do or catch what it means is i think this function is safe to throw with no errors and if you're wrong in this case i am wrong uh you're risking a very fatal error here this is what's an actual full-on crash here um so you've got to be really really sure and practice that's actually fairly rare there are a handful of places i would do it personally but nearly always i would not i would make sure i use a regular try and do a do block like that instead and catch the errors carefully so be careful around that you want to know exists but broadly speaking you don't want to do it when it comes to catching errors down here you always have to have this catch block to handle every kind of error remember we don't know what check password is going to throw we can see it's a password error but we're not saying that the way the function is defined and so swift will say it could be anything at all you can if you want to look for particular errors so you can do custom messages for example i might say i want a dedicated catch block for password error dot short this will do print please use a longer password then we'll say catch password error obvious print i have the same combination on my luggage and then this catch all at the end sometimes comically called a pokemon catch because you've got to catch them all got to catch all errors um i'll press play now and it'll be run by and it'll jump to this catch block that's the one that was actually thrown and we put in here instead as you progress you're going to see how throwing functions are baked into so many of apple's frameworks so even though you might not make them yourself having your own you know throwing function like this you at least need to know how to use them it does matter i would say uh most of apple's own errors that get thrown do have a meaningful error message you could show to users if you wanted to to provide some context or at least put into a log file somewhere swift automatically makes us available to us in an error constant and it's common to read that inside your prints or logs if you want to i could say print there was an error error and in particular you want to look for dot localized description which is the description of what went wrong in you know plain language using understand i won't have one here because it's our own errors obvious and short but apple's own ones will have meaningful localized descriptions you can work with if i temporarily take out my other catch blocks it'll run this last automatically and i'll print out the operation couldn't be completed a generic error message we haven't got a localized one ourselves you
Info
Channel: Paul Hudson
Views: 9,351
Rating: undefined out of 5
Keywords:
Id: T-UTLMKx2wc
Channel Id: undefined
Length: 11min 15sec (675 seconds)
Published: Thu Oct 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.