Error Handling | Learn to Code In Swift

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello this is matt from matt heaney apps and in this video we'll take a look at error handling in swift so we'll take a look at exactly what it is why we need it and how we can use it to be nice and prepared for any situation that arises when users get their hands on our apps for this i have a blank playground all set up and ready to go so a boot up a playground and let's get to work so in this video like i said we will take a look at error handling with error handling we can set our code up in a certain way to handle things that don't quite go as planned with error handling if something doesn't quite go right we can throw an error which we can then catch and handle in a graceful way this is essential for good code and for building good apps the important thing to remember when you're building apps is that there is always a risk that something will go wrong so we need to handle this with error handling you see graceful ways of handling errors all the time maybe without even realizing it say for example you're trying to post to a social media app and something goes wrong chances are you're going to get a pop-up that will explain the error that is a much more graceful way of handling this error compared to the app just not really doing what you expect or perhaps even crashing that is a sort of outcome we can achieve with error handling so let's take a look at this in action and you'll see exactly what i mean for this we will use a similar example than in the last video and let's pretend we're building a shopping app where a user can purchase a whole bunch of good stuff in today's example we will set up a user and an item that this user wants to purchase we will then allow this user to try to make that purchase now even in a situation as simple as this multiple things can happen and there can be multiple outcomes some good some bad for example the user might not be able to afford the item or the item might be out of stock or neither of these things might be the case and the user can successfully purchase that item in this video we will use error handling to cleanly and gracefully handle each of these situations let's take a look so for this example today we need a few new classes one for a user and one for an item let's quickly set this up so what a brand new class called user and the only property that we really care about for our user today is the users available funds how much money do they have to spend in our store so we will have a variable called available funds which is going to be a cg float which we will set in the initializer for the user for this example today that's it for the user all we care about are those available funds we also want a brand new class for an item that we want to sell in our store class item and for the item there's two things that we care about a price and a remaining stock so how many of these items do we have left in the store so price is going to be a cg float and remain in stock is going to be an integer and again let's set these up through an initializer and let's link it all up just like so so we now have a class for a user and a class for an item in our example today we're going to have a user who will have a certain amount of funds available to spend and we're going to have an item we do have a price and a remaining stock and in this example we're going to make a brand new user and a brand new item and this user is going to want to buy this item let's make a new user and a new item the user for me will be myself so let's have let matt and this will be a user and for this example this user's available funds is going to be a thousand so another example this will be a currency and the item we will declare is going to be a mac book air this will be an item and the price for this is going to be 999 and the store currently has 10 remaining in stock so we now have a user and we have an item and in this example i want to buy the macbook air the user is going to try and buy this item let's add some logic in place for this have a brand new function called purchase item this will take a user to the user who wants to purchase this item and the item they want to buy the purchase logic today is going to be nice and simple first things first we're going to take the user and we're going to take their available funds and deduct the cost of this item they purchase this item so we have to charge them right so user dot available funds and we will deduct the cost of the item because we've now sold one of these items we want to take away one from the remaining stock of this item so item dot remain in stock minus equals one we then want to print a message to say this user has successfully purchased this item we then also want to print out the remaining stock of the item and the user's remaining balance so user has successfully purchased that item i'm going to do a couple of different print statements here just so we can keep it all on the screen i'm zoomed in on the code we're then going to say there is now item dot remaining stock left of that item the user's remaining funds is now then the user's available funds nice and simple right we have a function that will take a user we take an item and we'll purchase that item and then print out all the information that we care about to let us know that the user has successfully purchased that item nice let's use this to purchase an item so purchase item the user is going to be me and the item i want to purchase is the macbook air let's hit play and let's see our print statements so we processed my order the user has now successfully purchased that item purchased i'm making typos everywhere nowadays there is now nine left of that item the user's remaining fund is now a pound which makes sense i had a thousand pounds to play with and the macbook air cost 999 pounds so sweet our function is now set up and the user can purchase an item and everything has gone to plan but that isn't always going to be the case even in this very very basic example there's two major things that can go wrong what if the user can't afford this item okay so say for example it was the end of 2020 apple just announced a new macbook airs with the m1 chip and they announced the price in dollars right so i've made an account on this website to buy a macbook air and i've done my conversions from dollars to pounds wrong and i only have 900 pound available to spend but the item is 999 pounds right in this setup if we was to hit play again i've still managed to successfully buy this item but now my remaining fund is minus 99 pound that's an issue we've now sold this item to a user who can't afford it also let's assume i do get my conversion calculation right and i have to correct funds but by the time i do all the maths everything's sold out i can afford this now but there's no stock left let's hit play and see what happens again we've successfully sold this item to the user but the stock is now minus one the problem is we've successfully sold this item to the user when we shouldn't have done there's no stock left i'm going to end up with a very very unhappy user and possibly some legal action we've just charged the user almost a thousand pounds for an item that we can't sell them so just in this very very basic example there's already some situations that we have to handle some errors in our process that we have to catch and handle gracefully so let's polish off the logic in our purchase item function to make sure this doesn't happen let's try and catch some of these errors before something bad happens so we're going to do is we're going to say in this function if either the user can't afford this item or if we're out of stock we're going to throw an error then when we call this function if something goes wrong and we throw an error we have to catch the error and handle this error let's take a look to do this there's three major parts to start with we have to throw an error so before any of this logic we're going to do a check we're going to say if eva the user's available funds is less than the item's price or to double pipe signs the items remain in stock is less than or equal to zero then let's fro choose the keyword throw an n s error which is just a standard error so if either of these things happen if the user can't afford the item or we do not have enough stock to fulfill that item we're going to throw an error at this point here the function will exit and nothing past that point is going to happen the function will know that something has happened that we will class as an error in our process and to throw it back to whoever's calling this to handle it now when it comes to throwing errors only certain functions can do this this is really important because when we call the function we need to know if it can throw an error or not simply because when we call this function we need to know if it can throw an error and if it can we have to handle it to make a function be able to throw an error we have to include the keyword froze here this function has the ability to throw an error now we can do this that's part one and part two done are setting up a function to throw an error we have some conditions that can throw an error and then we mark the function as having the ability to throw an error then when we call the function we have to do something a little bit different straight away when we call purchase item passing in a user an item we're now getting an error which says call confro but it's not marked with try so this function here we now know one or two things is going to happen we can either successfully purchase an item or an error will be thrown because of this we can't just say go purchase an item and always expect it to be successful instead we have to say to our code go and try and do this if you can sweet lovely we can crack on if you can't we will have to handle an error because something's gone wrong so what we have to do is we have to wrap this into a do catch block let's take a look so we will say do open curly bracket and let's pop this function call into this now before we call this we're going to use a keyword try so we're going to say to our code do the following literally plain english do the following and try and do this if you can do this then good the user is going to purchase the item but if an error is thrown then we have to catch it we will throw an error and we will catch it by saying catch open curly bracket and drop a line in the catch block what's going to happen is if we throw an error from this function this here will land here now if we try and do this function here and we throw an error this block of code will run the catch will run when an error has been thrown which will happen if the user can't afford the item or if we haven't got enough stock left so here what we can do we can print there was an error so now we're handling the situations a bit more gracefully now obviously in an actual app you wouldn't just print a statement you might make a pop-up appear or edit your ui to indicate what has happened let's see this in action let's reset our stock to 10 so the user has enough funds and there is enough stock left let's hit play and as you can see the user has successfully purchased the item this happened they purchased the item but now if we can't afford the item so the available funds are less than the item's price this here will be true so let's throw the error let's not execute any of this code and instead let's catch that error in our catch block there was an error saying for the other condition the user might have the correct amount but we have no stock left we can't process the order so we're gonna throw an error rather than process our order we're gonna print there was an error we're now stopping the user from purchasing that item with error handling and we are handling the situation we would do catch block so this is better right the user can't purchase an item they're not supposed to purchase anymore the problem is it's not all that graceful this is incredibly vague all we're doing is saying there was an error say as a user you're trying to purchase this item and that flashes up you're not really going to have a clue what happened and you're just going to try and make the same purchase again we want to be able to tell the user why there was an error we want to tell them if they haven't got enough funds or if we run out of stock we want to be able to throw different errors depending on what happened to be more descriptive in our catch block down here so rather than saying there was an error we want to tell the user something went wrong you haven't got enough for this item or something went wrong we haven't got enough stock left that is significantly clearer than this error here so how can we do that well rather than throwing this kind of very standard error instead we want to set up our own errors that we can throw so before our function to purchase an item let's declare a few errors that we want to throw for this we need an enum which we will call something descriptive so purchase error and for this what we have to do is make this enum conform to error now we can use any case in this enum as an error when it comes to throwing errors in functions so let's add a few custom errors that we want to throw here so it's an enon these will be cases and one of these as we just discussed is if the user hasn't got enough money to purchase the item so this error is going to be called insufficient funds so now rather than just throwing an ns error we could throw an error called insufficient funds the other example of an error today is insufficient stock like so and just like this we have created custom errors that we can throw in our functions that have the ability to throw so now back into our purchase logic rather than doing this we can now break out this if statement into two different if statements like so so one if statement for if the user hasn't got enough funds for this item and one for if we haven't got enough stock if the user hasn't got enough to purchase the item then we're gonna throw purchase error insufficient funds our new error from here which is of course a purchase error if we haven't got enough stock remaining then let's throw purchase error dot insufficient stock we are now throwing more descriptive errors and that's really really important to be able to handle different errors in different ways then when it comes to our do catch block to run this function rather than just saying let's catch any old error we can now catch particular errors so let's try and do this if we throw the insufficient fund error then we're going to catch insufficient funds and here we now have a block of code that will run if we catch this one particular error so now we can print something a little bit more custom error please add more funds to purchase this item so now if we throw this error we can print more of a custom error message but we know there's multiple errors that can be thrown so we can do we can chain up our catch blocks so after this catch block we can add another catch block if he was to throw the insufficient stock error and we catch it then we're gonna print error item currently sold out then what we can do add another cat block for if we somehow caught an error which isn't either of these which i get in this example today isn't going to happen but it's a really important thing to know so this can almost act as like a default catch block for if we catch any error there isn't any of these cases and even though this isn't going to happen in our current logic we might add another error case to this in the future so let's play it safe and let's add a default fallback just in case this one any other error was thrown so we can't really add the details so let's just say error please try it again soon we now have a do catch block which handles multiple errors being thrown if the function that we try and do throws this error here then handle it in this way if it throws this error here then handle it this way or if it was to throw any other kind of error let's handle it this way let's quickly see this in action so currently the user has enough funds but the item doesn't have any stock left so when we try and purchase the item we're going to throw the insufficient stock error i'm going to catch it and handle it in this way like so if we do have some stock left but the user can't afford it then we're going to throw this error we're going to catch that particular error and handle it this way just like so or if the user has enough funds and we have an item in stock then no errors will be thrown and everything goes through and the user can successfully purchase this item so we have now created custom errors and we are catching all the different errors that can be thrown from that function so we now have these errors that are a lot more descriptive with these errors we know exactly what's going on and we can handle each error in an appropriate way to let the user know exactly what is happening but we can go one step further in making these errors as descriptive as possible one of our errors is insufficient funds we're telling the user that they have to add more funds to purchase an item wouldn't it be good if we could tell the user exactly how much more they have to have in order to purchase this item well we can do that what we can do with the correct error so in this case our insufficient fund error in our purchase errors we're going to add an associated value to this that means whenever we use this case we have to provide some additional information let's take a look how this works so case insufficient funds let's open up a bracket and let's state what additional information this error needs so additional funds required which is going to be a cg float now whenever we use the insufficient funds error we have to provide this information a cg float for how much more the user needs to be able to purchase this item and now when we try and throw this error we have to pass in that information so let's re-enter this back in to get that to auto-complete for us and as you can see when we throw an insufficient funds error we now have to pass in how much more the user requires that is a simple sum where we're going to take the items price and take away the user's available funds to get how much more the user needs to purchase the item then what we can do when we catch this error in addition to catching the error we can also get our hands on that piece of information we're passing along with the error to get access to it we're going to do brackets at the end of this and we have to declare somewhere to hold that value that we're passing so in the brackets we would declare a constant and we'll call this additional funds required now additional funds required is going to be set to whatever that value is that we passed down when we throw this error we can use this in the scope of our catch block so now we can change this error to say something like error please add an additional additional fund required to purchase this item so now if they are a hundred pound short for example it would say please add an additional 100 pound to purchase item it's so descriptive so now let's say the user has only 900 pound in their account and we know from this this item is 999 pound that means the user is 99 pounds short they come along they try and purchase the item and they can get an error and it's going to say error please add an additional 99 pound or whatever currency you want to pretend our example is using today to purchase this item straight away the user will know exactly what's happened and they can go away and they can fix this issue and come back and hopefully purchase the new item so that is how we can throw errors with custom errors and of errors which hold a value and that wraps up this video as always any questions or any comments post them down in the comments section or if you have any other swift areas that you'd like me to talk through in one of these videos let me know down in the comment section as always if you liked watching this video make sure to hit that like button hit subscribe and thank you for watching i'll see you next time goodbye
Info
Channel: Matt Heaney Apps
Views: 531
Rating: undefined out of 5
Keywords:
Id: a2ibWtPsryw
Channel Id: undefined
Length: 23min 7sec (1387 seconds)
Published: Wed Mar 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.