Swift Error Handling - Do, Try, Catch - iOS Interview Question Series

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everybody we're back with another video in my iOS interview question series and today we're going to be talking about error handling and more specifically the due try-catch syntax we're going to talk about when to use it how to use it what it is all that stuff let's dive in alright so in order to show off the do try-catch syntax and how to use that we're going to use a pretty common example and that is logging into an app now forgive me I didn't go ahead and build a fully functional you know login screen that is connected to a back-end so we are going to kind of fudge some stuff a little bit but you'll get the idea so as usual I'll walk you through my starter project the storyboard here is pretty self-explanatory just have an email text field password text field and a login button I do have some helper methods so I have a string extension that is a regular expression to validate an email this is to make sure the email is in a valid format so in case you write just you know Shawn Allen at Gmail you know without the com this will catch that kind of stuff feel free to steal this if you like and my other helper is for just showing alerts just so I don't have to type this code over and over again you'll see this in action later and then going to our view controller just have the outlets for my text fields and then it's going to clean it up a little bit and then I have my viewdidload method and then I have the login button tapped IB action so that is a quick rundown of the project but before we get into all that let me show you a quick example of a function that requires do try-catch now the key here is that some functions will do what's called throws let me show you it real quick let's say we're trying to convert an image into data so we would say let image data equal data and then we initialize that with contents of and then URL now here's the key see how this says data contents of URL and it says it throws here's another example of a function that throws anytime you see a function that throws you're going to be required to do a try and most likely a do try cache block so this is the key here is looking for this keyword throws alright so let's go ahead and pick that function here and let's go ahead and just do a URL you know file path with string and then my file path what this does if you're not familiar with this little bit of code this is basically if you have an image at a file path in your app this will just convert that image into data so you can use it in other ways this is just my example of a function that Apple uses that throws so we can show the do try catch block after we get through this quick example I'm gonna do a custom example so you'll really understand it after that but this is kind of like the intro so you see I get two errors here one just says I'm not using the variables so let's ignore that one and click on the two and see here it says I can call throw but it's not marked with try and the air is not handled so if you choose a function that throws Xcode will actually not let you proceed unless you handle it with a do try catch block so let's go ahead and implement that again this will just be a quick intro and we'll dive into it more later so you want to start with do open and closed brackets then we're going to go ahead and cut and paste this into into the do block now we have to preface this with trot here over here so what we're trying to do is we're we're trying to get data contents of URL that's what we're going to try and then if that try fails then we go into the catch block so it's actually very similar conceptually to like an if-else statement so one way to look at this would be you're telling it to try this little bit of code if it's successful you know now you have the image data variable you can you know do whatever you need to do with image data because you have it so that as long as you're in this block that means the try it was a successful try so to speak everything worked out fine if the try is unsuccessful and you throw some errors that is when you go down into this catch block and here's where you need to handle the air appropriately so in this case you would just do you know maybe you would want to print error dot localized description and all this warning is because I'm not actually using this variable yet so let's go ahead and actually run this to see what happen to console okay now as you can see I just reuse my login button tapped function so I'm just going to tap this again and you'll see the error pop up and it went into the catch block because I printed the error localized description says the file you know my file path because this is obviously not a correct file path and something I just made up couldn't be open because there's no such so in real life if that happened now you'd probably actually want to show you know a pop up show show pop up with air this way the user you know gets a description of what actually happened in what's going on you don't want to just print to the console so okay that was just a real quick down and dirty introduction of the do try catch again we're gonna go through a more in-depth example here in a second that's more custom using an enum with error cases but before I gave a more complex example I wanted to give you guys this introduction so you at least had an idea of where things were going so again the key here is this function here this data contents of URL it is a function that does what's called throws and any function that throws you have to wrap in and do try catch block with a caveat you can just do a try sometimes we won't get into that right now but just just know that if a function throws you're gonna have to handle the air somehow most likely in a do try catch block so again you wrap it in this do block this part right here is if the try was successful and what's in the catch block is if it was unsuccessful and you handled that so that is the basics let's dive into a more complex example so in this more complex example we're going to handle a couple of special air cases that have to do with our login screen in order to do that we're gonna put our error cases in an enum so let's go ahead and type that out real quick alright so here's my you know you see I have a called it's called login error it's conforming to the error protocol and then I have the different cases and obviously when you're filling out a form there are more cases but these are just some simple ones I wanted to demonstrate for you so we have the incomplete form this is when you know they forget to type in an email or password invalid email is for like I mentioned before when their email just isn't right like they forget the dot-com at the end or they forget the @ symbol and an incorrect password length as you know sometimes you have to have a password that's eight characters long so this is handles that error case so again just a couple of the typical cases you'll handle during the login process so now let's go ahead and create our login function that's going to throw an error remember I said this is the key if a function throws that's when you have to handle it with a do try catch block so we're gonna go func login and then here's the keyword throws and then you do your normal open and closed brackets so now we've designated our login function that it throws and we know bori that uses this function is going to have to handle the air so if you're wondering when you would want to use throws on a function I like said if you're writing a function and you know it's gonna be able to throw a couple different errors you want to handle that that's probably a good case for that if your function doesn't throw any errors then you don't use throws so I'm gonna create some variables real quick that's gonna make the rest of the function easier to read and so forth so you know text field text and then let password goal password text field dot txt again these are just convenience variables you don't necessarily have to do these now like I said I didn't build a fully wired login screen that connects to a back-end or anything like that so this is kind of where I've to fudge it a little bit so right here let's just you know pretend this is great code that logs in my user it really is amazing okay so that is my code that logs in the user again forgive me for fudging that but before we log in the user we want to check for all these errors that we just talked about up here on lines 13 through 17 all these login errors so let's go ahead and start doing that so the first thing we want to check for is this incomplete form and what this really means is that you know is the password text field and email text field empty so let's check for that so if you know it's empty or password that is empty and again this email and password variable is a convenience variables I just created out right above it so if this is in fact the case if email is empty or password is empty this is where we want to throw an error and the error we want to throw is login error dot incomplete form you see here's our three errors in our enum so we're gonna throw a log in incomplete form and then you're gonna see how this all ties together when we actually call the login function in log in button tapped up here on line 26 and 28 we'll get to that that's the second half so that's the first check we want to do we're checking to make sure our email and password fields actually have something in them if that isn't the case let's go ahead and make sure the email is valid so if email dot is valid and again this is valid property that I added is part of my extension on email which let me show you here remember this is the helper function I talked about it's using a regular expression to make sure the format of the email is correct again to make sure there's an @ symbol make sure they actually have the comm etc again feel free to steal that from the source code if you want it's very useful I use it in pretty much all my projects so if email is valid email actually we need to put the bank operator in front of that because we want to see if it's not valid so if email is not valid then we want to throw login error dot invalid email makes sense right and then the last one the check is we want to make sure our password is of the correct length so if password dot okay I'm in Swift three right now so floors coming out right around the corner insta before you can just do password dot count but since we're still in Swift three characters dot count so again if you're watching this in Swift for you don't need password characters that count just D password count is less than eight let's say our password requires eight characters if that is the case you guessed it we're gonna go ahead and throw login error dot incorrect password length and then if all these checks pass then we're gonna execute my amazing code to login the user okay so a quick recap here on lines thirty to forty nine here we have our login function and again the key here is it throws so now I'm gonna have to handle it in the do try catch block and then you're gonna see we're gonna have to catch all the different error types so the different error types are you know this login incomplete form login error invalid email and then login error incorrect password length so let's go and call our login function in login button tapped so when the login button is tapped we're gonna go ahead and call the login function now again Xcode is gonna yell at us hopefully yep and like I said if you designate your your function with throws here Mexico's not gonna let you not handle the air that's why you want to only use throws when you for sure want your errors handled it's a very dangerous might be a strong word but you know use caution when using this function so as you can see we get the air can call throw but it's not marked with try and the error is not handled so basically Xcode is saying yo dude handle this error let's do that so again we just go ahead and wrap it in the du and then we want to try cool and then we want to catch and then like you saw before I just had the one catch block and this was kind of like a catch-all for the heirs however in the case of our login you saw we had three different you know login types so again just it's very similar to an if statement so this is kind of like a else--if so now we want to catch login air dot incomplete form when if if that is in case the air that it catches what do we want to do we want to show an alert specific to that air again remember I showed you this alert helper at the beginning this is just so I don't have to type this over and over again and you'll see how this comes in handy and again feel free to steal this I use this all the time too so I just do alert dot show basic and then the title here I'll just put in complete incomplete form and then the message I will be please fill out both email and password fields and the view controller that is presenting this is going to be self it's going to be this view controller so that was catching the incomplete form error and I'm gonna go in fast-forward the typing for the next two and we'll review it alright let's review our do try catch block so again because the function login throws we have to handle it with do try catch so what are we doing we're trying login so if login was successful this is actually probably where we would you know transition to next screen because it was successful but again everything in this block right here is what happens when the try is successful and then all the catch blocks are when the try is not successful and then you can either only use one catch block to have like a catch all like a general error or if you have specific errors you can do what I'm doing here in catching the specific errors and in handling them appropriately which will see an action when I run the app here in just a bit because we're just about done so these are all very similar like I said I'm just catching the invalid email so again this is it the format of the email is invalid and then I'm just showing an alert with the title invalid email format in the message please make sure you format your email correctly and then down here with the incorrect password length again just showing an alert with the title password too short and then you know password should be at least eight characters and finally the catch block does have to have a final catch that's not specific to an error kind of a catch-all if you will that's why this error message is pretty generic you know just as unable to login there was an error when attempting to login so again here's an example of handing some pretty typical login errors let's go ahead and run the app and see this in action okay so I got my app up here let's test the first one like I'm not gonna enter anything empty so hit login and then you get the pop-up incomplete form please fill out the email and password fields okay that's exactly what we expected now let's just type you know Shawn allen dev at gmail no com we'll just forget about it and here's my password login and I'll email format you know so you see we're getting the correct errors because we handled them with the specific error cases let's do let's go ahead and add the com so now I have a valid email and then they should do a password of three characters because that's obviously too short hit login invalid email format look I missed that but my air is caught it I put a space for some reason up here in Shawn allen dev so if I get rid of space now my email format is correct but my password is too short so I should get password too short password should be at least 8 characters and then now if my password is a characters nothing is going to happen because none of my errors got caught as you can see I'm tapping it nothing happened no error pop-ups this is where my magical code down here is getting executed because everything went fine so there you go that's the basics of the do try catch syntax hopefully if you get this question in an interview you'll crush it if you have any further questions about it go ahead and leave a comment down below if you found this at all useful go ahead and subscribe I put out new videos all the time
Info
Channel: Sean Allen
Views: 42,768
Rating: undefined out of 5
Keywords: swift error handling, swift 3 error handling, ios error handling, iOS interview questions and answers, ios interview questions, swift interview questions, error handling in swift, error handling in swift 3, error handling in swift 4, swift 4 error handling, swift tutorial, ios interview questions in swift, swift interview questions and answers, iOS Development, iOS Developer, Xcode, Xcode tutorial
Id: Lrc-MX8WgNc
Channel Id: undefined
Length: 14min 58sec (898 seconds)
Published: Thu Aug 31 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.