Exception Handling in Java Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys john here how's it going today we're going to talk all about exception handling in java we're going to be going over what exceptions are how you can handle them with what's called try catch blocks of code what happens when you don't catch them right away some different types of exceptions and what's called the exception hierarchy and finally we're going to learn about finally blocks and what they are and what they do and some super crazy unexpected results you can get if you don't understand what finally blocks do exactly you're definitely going to want to stick around and check that out but first what is an exception an exception is a generally unwanted event that interrupts the normal flow of your program here's a quick example of some simple code that would cause an exception we're trying to parse an int from the string ants you might be familiar with this integer parseint method it just takes a string that you pass in that usually contains a number like one or you know whatever some kind of a number that's uh parsable into an int but here we're trying to parse the end pants let's go ahead and run it we can see we get this number format exception because it can't make a number out of pants trust me try as you might you can't make a number from pants just has to blow up and throw an exception i can't do what you want if you the programmer don't handle this situation your program blows up prints some exception information to the console here that we're looking at and terminates that's it game over but now that is where exception handling comes in so instead of just blowing up and terminating the program you can catch the exception that's thrown and have special code to handle that situation elegantly instead of blowing up in java we do that with try catch code blocks and they look like this first you have a try block and inside the curly brackets here you write any code that you want that might cause an exception in some situations and then underneath that you have a catch block to catch those types of exceptions and then write any code that you want to execute whenever that type of exception happens going back to our pants example from before we go ahead and paste in the code that causes the exception to be thrown in this try block here of course same as before this piece of code will throw a number format exception when we try to parse pants into an integer so we include this catch block that says we will catch a number format exception if it is thrown in the try block get it throw an exception catch an exception it honestly took me way too long into programming to make that connection so in our example when this number format exception is thrown the code inside of our catch block will execute and the program won't have to terminate here so far we don't have any code in our catch block so let's go ahead and add some well basic thing you might want to do is print out a message to the user i wanted to say something like hey dude you can't make an int out of that stop trying to make it happen all right so now when our program tries to parse an end from pants it'll throw an exception that our catch block will catch and we'll see the statement print out let's go ahead and run that and here we see the printout but the program didn't terminate we don't see the big angry stack trace of the exception that we saw last time also it's important to note that if an exception is not thrown this catch block will never be executed so if we go ahead and change this to a normal int string of one we can go ahead and run our program again and we can see we got no output at all the program just finished we can add a little statement here at the end just to prove that the the code is actually running and here run the program again you can see that we finished the program but we never executed this catch block because there was no exception thrown there was no problem so there was nothing that had to catch the exception and handle it it's important to note that the catch block here this type of exception in your catch block uses something called the exception hierarchy and that just means that the type of exception that you put in your catch block will catch only exceptions of that type or any subclass of that exception so as a quick example you'll often see just catch exception e and you can name this exception variable that it catches anything you want often the convention is just to use like the initials of the type of exception that you're handling that's why number format exception was nfe and for exception you'll see exception e so this means it will catch any type of exception at all any class of exception that extends from exception and all of them do this will catch all exceptions and the way we had it before number format exception will catch all types of number format exceptions there could be subclasses of number formatted exceptions for specific types this would catch all of those underneath that umbrella and taking a quick look out of the documentation for a number format exception we can see the we can see the hierarchy that it comes from of course object is the parent of every single class in java and underneath that we have throwables and then right underneath that exception and every type of exception in java is going to be underneath that and a few steps down we find the number format exception one of my favorite terms in programming comes from this when you're catching every type of exception here i've heard it called pokemon exception handling because gotta catch them all now you may have noticed from this uh class a hierarchy here there's also these throwables so it's important to note that there are actually two types of throwables there are exceptions that we're going to talk about here and also errors generally you don't want to be catching errors so you might see some programmers saying catch throwable t here instead of exception e and that's generally not recommended you don't want to be catching just the all throwables because you don't want to catch errors you just want to catch exceptions uh it's it's enough to say it could just cause some really strange unexpected behaviors now in your programs you don't necessarily need to catch your exception right at the exact line that it happens when an exception gets thrown and it's not caught immediately in the method that it's in right then it'll get thrown up to the method that called it that's called the call stack throw an exception goes up the call stack until it is caught by a catch statement like this so for example if we had all of this code and it was in a method just called like get int or something right now we have our try catch in that method but we don't have to often it makes sense to have your try catch in the method that calls the method that's throwing the exception we could refactor it to look like this so what happens here is when this line throws a number format exception and it's not caught immediately in this method it gets thrown up the call stack that just means it's thrown to the method that called this method and in here it's thrown back up to this level in the main method and here we have a try catch so it's going to get thrown out to this level of the call stack and caught by this exception handling code here so let's go ahead and run it yeah our exception handling still worked we've still got the hey dude comment and the code ended with no explosions of an exception and no stack trace printed out to the console another cool thing to note is you can catch multiple types of exceptions with multiple catch blocks so you might have your first catch before like a number format exception and then you could have another block just copy that and paste it to catch a like say maybe a null pointer exception this allows us to have different behavior depending on the type of exception that was thrown say you want to catch different types of exceptions you just want one bit of code to be able to handle multiple different types of exceptions well you're in luck ever since uh java 7 you can have what's called a multi-catch statement and to code one of those we can just get rid of our second catch statement just have number format exception and then to denote the multiple types of exceptions you want to catch here in this block use a bar character the same character you'd use for or statements number format exception or null pointer exception and run the same exception handling code in either case and that way you avoid code duplication while still being able to catch multiple types of exceptions pretty cool finally let's talk about finally blocks but if you want you can include a finally block after your catch block that'll look like this look very similar just finally this all this block does is to contain code that you want to execute whether there was an exception or not it will always execute always always always just as an example let's go ahead and put let's see in the finally block right here so we can see when the finally block is executed just to make things simple we're going to get rid of our extra method here and just put this statement that causes the exception directly in this try block now what will happen is this ants parsing will again throw an exception a number format exception so let's get rid of this null pointer exception catching this will catch the number format exception print out the message to the user and then it will run the finally block again the finally block runs whether there was an exception here or not let's go ahead and run our program and so you can see we caught the exception printed out the hey dude and then printed out in the finally block and real quick an important thing to note when an exception is thrown the rest of the code after that in the try will not be executed so for example we can have a print statement here that says after parsing dance now if we run our program you'll notice it never reaches that piece of code it doesn't get here because an exception was thrown here and out to this catch statement so anyway getting back to our finale after it ran what was in the try which threw an exception ran what was in the catch it finally ran what was in finally and it will execute that whether there's an exception or not so we can change this back to a 1 so an exception will not be thrown run our program now we see this this catch block was not executed but we have after parsing pants this didn't throw an exception so it could print this statement and then the catch code never executed because there was never an exception thrown but it still executed the finally code no matter what now when i say no matter what i mean no matter what you can literally have a return statement here in your try you would think that after this code executes and that you get to return it would just return out of this method and not execute anything else but it will always execute your final block see even though you have a return statement here after parsing pants it still runs your finally and here's an even weirder example of the same thing what we have is a simple private method that just returns an int called print a number and and all we've got here is a try catch finally statement we're in the try statement we say return three in the catch statement we say return for and in the final statement we say return five of course what's in this try block won't cause any exceptions so the catch block should never get called but in the try block we're saying return three and in the final block we're saying return five and our main method all we're doing is printing out the result of this method call so let me know what do you think the result of this method should be the answer is five remember what i was saying is the finally code always executes a reach and that and that means that a return statement in your finally will override a return statement in your try or your catch blocks and that could lead to some super unexpected situations so there's something to keep in mind most of the time you are not going to need a return statement and you're finally blocked generally just avoid it and it's also a good java interview question to know about you could be asked about this know the type of behavior that finally has but after seeing this you might be thinking goodness why would i ever need a finale for most of the time you don't most of the time a try catch block is all you need you have some code you want to try that might throw an exception and the catch block handles that exception that's all you have to do but there's certain special situations where you might want to finally block maybe in your try you're doing like a database call or some file input output in your try statement and you always want to close your connection like to the database or to the file stream because that's something you would always want to do um if there's some database issue or a file issue you always want to close that connection and that's kind of thing you would put in your finally block 99 times out of 100 you're probably just going to have a try catch statement if you got some value from this video please let me know with a like it is amazingly appreciated and hit the subscribe button if you'd like to see more java tutorials as they come out see you guys next time
Info
Channel: Coding with John
Views: 147,133
Rating: undefined out of 5
Keywords: exception handling in java, java exception handling, exception handling java, java exception handling tutorial, java exceptions, java exception class, exception handling, java, codingwithjohn, coding with john, java made simple, java for beginners, java made easy, learn java, learn to program in java, learn to code, learn exception handling in java, programming, java tutorial, java exception handling best practices
Id: 1XAfapkBQjk
Channel Id: undefined
Length: 13min 20sec (800 seconds)
Published: Wed Dec 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.