Learn Programming in Java - Lesson 16: Exceptions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello again and welcome my name is Michael fudge this is our learn to program in Java series we're up to lesson 16 lesson 16 will cover exception handling on the agenda today for less than 16 we'll talk about errors what are they how do they occur exceptions what are exceptions and why you need them we'll talk about the try-catch statement which is a block of code we use to handle exceptions and then of course we'll look at best practices and reasons you should use exception management in your programming let's start out by talking about errors exceptions are designed to handle errors but what are errors errors are conditions which occur in your program and they cause that program to stop running or terminate we've seen this before where you type in bad input and next thing you know you see the red text in your program output and Java stops running your program sometimes we don't want our program to stop running we want to detect the error handle the error condition and then continue running our program there's really two types of errors that occur there's user error which is bad input somebody types in something or does something that the program cannot handle and therefore it terminates and then there's programmer error which is we write our code in a way that a certain condition is hit and then an exception occurs and we've seen this kind of thing when you're looping through an array and you index a value of that array outside the boundaries of the array you get an index out of range exception some of these errors are are easier to handle than others and some are not it really kind of depends on the circumstances but the good news is is that every single error that we do that we can possibly encounter can be handled the way we handle these errors is with the try catch finally block so let's explain this in a little more detail when you're writing a program if that program has a chance of causing an error Java will raise what's called an exception and is a variable of type exception when the error occurs if we don't handle the exception we just get the red text that we usually get when you run the output and then the air the exception is displayed in our in our console window if we want to if we want to handle our exception the code that possibly could generate the error should be surrounded by a try block you can see I have a try keyword and then a block if I put the code between these two curly braces that has a potential to raise the exception or throw the error as we say if I put the code in there when the error occurs rather than terminating the code we'll jump down to this catch block where I can then do something with the exception that I've caught I can either print it out or log it or clear whatever air condition may or may occur so that I can continue running my code the last bit of this try catch finally block is obviously the finally keyword and what happens in the finally block is usually clean up code it's code that we run regardless of whether tri finishes successfully or catch the catch block is actually the code actually jumps down to the catch block regardless of whether or not that happens the finally code always executes this type of block is much cleaner than efficient then what we used to do with error checking before constructs like try catch finally we would resort to things like putting additional parameters and our methods that detected error conditions we put a lot of if statements around to try and catch really weird boundary errors and things like that it was really a mess the beauty of this type of block is that you don't really have to worry about errors you just have to say you just have to ask yourself can an error occur in this portion of my code if the answer is yes then you surround that code with a try catch finally block then deal with the exceptions as they occur so you might be asking yourself at this point when should I handle errors using exceptions and the answer is pretty clear when your code has a chance of causing an error and you need to handle that error gracefully that is you do not want your program to terminate you should probably use a try-catch block when you handle the exception you will prevent your code from terminating and you could usually do things like try to clear the exception try and clear the code out that caused the exception you probably want to log the exception so that you know these types of errors are happening in your code either by printing them to the console or writing them to a file some examples of when you want to handle errors usually anytime you're getting input from the user because you don't know what you don't know what the user is going to do so you want to try to handle all the situation's of a user input any time you're really writing to a file because you never know is the disk not going to be available what I'm trying to read that file or write to that file whenever you're trying to access resources outside your control like let's suppose you're programming a game and you're using a gamepad you might want to verify via a try-catch block that the gamepad is first connected to the computer before you start to ask for input from the gamepad these are all examples of when you'd want to use an exception but generally speaking when you think about your code you have to ask yourself is there a chance that I can have an error in this code and if so do I want to handle that error or am i okay with the system just stopping this program from running and just reporting the error at the console okay it's demo time I have two demos that we will go through the first demo will just walk you through the basics of exceptions and the try catch finally block and the second example will show you why you want to make your own custom exceptions so that when you throw particular errors you know the source of the error because of the name of the exception okay let's get started Here I am in my NetBeans IDE and I have a project that I've opened up called exception basics and one class called exception basics and I'm just going to kind of walk you through the basics of why you'd want to use an exception to handle various input now I could write this type of program I've written it before but you probably never thought long and hard about what happens if someone doesn't follow the instructions you give them so I'm going to do a little copying and pasting so you don't have to watch me type okay my typing is complete and how many times have you seen a program like this before where I asked you to enter an integer I accept that integer and then I simply print out what you entered I mean you've seen this program run quite a few times already and when I run this program you'll see it says enter an integer and I can type in a 5 and says you entered 5 that's fantastic the real interesting thing is what happens when I don't enter an integer if I run the same program again and then this time it says enter an integer and I'm going to enter my name and you'll see it's rose an exception called java.util input mismatch exception so let's see if we can write code to handle this exception and rather than exiting the program like this with this obscure you know exception and stacktrace it kind of gives the user a little more graceful message so again the rule of thumb is the code that can throw the exception is right here so what I need to do is I need to take this code and then any dependent code so for example it's dependent on input which is up here which is of class scanner and I need to surround this with a try block so here goes try let's get the rest of this working and then I'm going to say catch input mismatch exception II now what do I want to do when I catch this well of course I need to include that so I just imported that up here what do I need to do when I catch this exception well I could do a couple of things but I think what I'll say is something like this how about you didn't enter an integer and I guess that's good enough for now let me just reformat my code there that looks much better now let's run it it says enter an integer and I'm going to put in Mike and now rather than you know barfing out a stack trace and an exception it it goes down here in this catch block handles the exception and then prints out this message instead if you don't believe me I can I can trace through it and show you if we go through it a line at a time so I'm going to hit f7 enter an integer Mike and you can see it jumped immediately into the catch block and I now have a variable e of type input mismatch exception and this variable e has a bunch of values to it so that indeed did work so you can see the value of exception management because rather than me having this program terminate I can gracefully handle the exception in code let's finish this example up by making it completely useful and surrounding this code with a while loop so that it keeps asking me for input until I enter an integer this is something that you probably thought about doing before but just weren't able to do now that you know how to use exceptions you can do this quite easily so first thing I'm going to do is I'm going to need some kind of condition that tells me it's time to exit and I'm going to use a boolean for that I'm going to call it dun dun is false so we're not done and I'm going to say do all of this while not done and let me reformat this code there we go so what I'm going to do now is I'm going to iterate over this code here until this is true right now it's until it's false right now not false is true so what I need to do is after I accept input if this throws an error it's going to jump down here and it's not going to execute this next line here if it's if I do type in it successful in it will go to the next line so done is true here I mean it looks kind of silly but let's just think about what happens it's going to do this do this you type in something that isn't an int it's going to jump down here then it's going to go back up here and repeat when you finally do type in int it's going to do this line of code here and then this is now going to be false and the loops going to stop so let's run it and then if you want we'll trace through it so enter an integer ten hahaha you didn't enter an integer how about Mike you didn't enter an integer five you entered five beautiful and let's just for for kicks let's put a breakpoint here and let's give it a debug so here we are scanner input and I'm going to step through this code now it's asking me to enter an integer I'm going to enter Mike now watch what happens when I press enter it's going to skip line 16 and jump right into the exception see that so now if I go back up here and continue and step through it again now it's asking me for an integer this time I'm going to put in a valid integer and now it drops down to line 16 execute this code here now my exit condition is no longer true because not true is false and I exit the do-while loop so that's how that works try/catch now let's add one last wrinkle here the finally finally the finally block always executes whenever the try or the catch executes and we generally use the finally block for cleaning up the code that we started inside the try block so imagine you do a bunch of work inside try but you only get halfway done because you throw an exception the finally block is where you can kind of detect what happened and then hit the undo button if you if you need to or sometimes maybe you start to work and try and then you hit catch and then because you caught the exception you undo everything but then regardless of whether try works or or doesn't work you need to do some cleanup code so you would do that down here and finally what I'm going to do in this case is just put a simple message for here so that you understand what what finally does and when it runs so this happens whether the exception occurs or not so let's run it one last time and ran integer and that says you didn't enter an integer and this says this happens whether the exception occurs or not see that and then I can actually enter an integer this time and it says this happens whether the exception occurs or not so it always executes the finally block regardless of whether try complete successfully or whether an exception is thrown inside try and the catch block comes up so that's try catch finally that's error handling via exceptions really not much to it in the next example we'll take a look at writing your own custom exceptions but before we go one thing I do want to make note of is you might be wondering well really isn't really this the only code that needs to be in the try catch block and I want to reiterate one last time that you should always take the dependencies the object dependencies and enclose those in your try block so for example the input object depends on the constructor up here that creates it if I do not put that constructor inside the try block when I hit the catch block for whatever reason and go back up here it's it's it's not going to it's going to it's going to cause problems because it's not going to know about this object because of object scope right this this object is outside the scope of these curly braces right this kind of goes back to when we declare variables in different scopes so you always want to make sure that those are in the scope okay for this next example I've written most of the code already I'm just going to kind of walk you through it and then maybe take you through a run in a debug of this code the difference between this code and the code that we saw earlier is that there are two catch blocks what I'm trying to do is catch two different kinds of exceptions and this is important because you don't want to catch general exceptions for example it doesn't make sense to just catch exception because then you you can't do different things based on that exception the better thing to do is to be as specific as possible as to the type of exception you're trying to catch and let me just walk you through what's happening here I'm asking you to enter an integer between 1 and 10 so when I run the program it says enter an integer between 1 and 10 and if I put in a 99 that is certainly not between 1 and 10 so what will happen here is if the number is out of range I'm going to throw an integer called throw an exception called integer out of range exception and this is a class that I wrote that extends system exception so when you want to make your own exceptions the only thing you need to do is make this simple class that extends system exception and now you've made your own types of exceptions and you can find conditions under which those exceptions should be thrown and then throw them so I type in 99 I press ENTER and it says your input value is not in the specified range which is the code that runs right here because I caught the integer out of range exception not the input mismatch exception I had a little brain hiccup there for a second the input mismatch exception occurs when you enter something that's not an integer okay for example let me run it again and I type in Tony you didn't enter an integer see that so all there is to it with this integer out of range exception is I've created a class called integer out of range exception and that is your honor out of range exception is an extension of what is normally just a system exception so there's a generic exception called system exception and I'm extending that with my own custom exception and then I'm using that exception here now normally we wouldn't you might say well Mike why wouldn't I just write if this then print something right and yeah I certainly could have said you know if I is between you know his eye is less than one and eye is bigger than ten you know begin a curly brace print this and curly brace but this is a big but the advantages of using exceptions is that while this code does exactly what I want today tomorrow I might not want to simply just print out your input value is not in the specified range I might want to do something else or something more sophisticated and by using custom exceptions all I know is I do my code and then if an error occurs I catch my exception and then I process my code in there I don't have to write that code in the body of all of my ifs one last thing to note is that you can print out the exception itself if you want for example let me just add this code here and what I'm going to do is print you didn't enter an integer and then print the exception itself because I want you to see what this looks like all right so let me run that let's enter a value of 100 and it says integer out of range exception see that and that's useful because now you can log which exception occurred by printing out the exception itself but rather than printing out to the console you could print it out to a file or some kind of other logging framework that you might use well thank you for watching this lesson on exceptions and errors in Java I think what you'll notice is that is that this is just the beginning when it comes to exceptions we had to introduce this lesson now because some of the code that we'll be writing in future lessons will be throwing exceptions and we need to understand the basics of exceptions before we can get into those those areas what I want to point out is this isn't everything that you possibly would want to know or learn about exceptions but the rest of the things we'll be learning by example as we do the other lessons that's why this is a relatively short lesson again thanks so much for watching post your questions comments and feedback on YouTube and we'll see you again real soon
Info
Channel: Michael Fudge
Views: 78,362
Rating: undefined out of 5
Keywords: Programming Language, Error handling, Exceptions, Best Practices
Id: R86ObiKhMNc
Channel Id: undefined
Length: 20min 47sec (1247 seconds)
Published: Mon Oct 21 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.