[00:02] everything you need to know about exception handling in Java so by the end of this video you'll be able to write Java code with confidence hi I'm MH hamadani and I've taught millions of people how to code through this Channel [00:14] at my online school code with.com this video is part of my ultimate Java Mastery course so once you finish this video if you want to learn more you may want to look at the complete course now let's jump in and get started [00:34] overview of exceptions first of all I'm going to add a package in this project I'm going to write all the code for this section in this package so let's add a section in this package so let's add a new package called exceptions as you can [00:47] see I've created packages for the other sections of this course you can find all these packages and all these files in the zip file that I give you at the beginning of the course now in the exceptions package I'm going to add a [00:59] exceptions package I'm going to add a new class called exceptions demo this is where I'm going to demonstrate Concepts here I'm going to add a public static void method called show I made it static so we can call it easily from the main [01:13] method without having to create an object okay now let's go to the main object okay now let's go to the main method and call exceptions demo. show now back to the demo class I'm going to create another static method [01:29] going to create another static method public static void say hello we give it a parameter of type string called name and here we want to print name in aric case pretty straightforward now in the show method [01:43] I'm going to call the say hello method and pass null which represents the absence of a value now when I run this program our program is going to crash let me show you so our program crashed we got an [01:57] exception or an exceptional event and the type of this exception is null pointer exception this is the root cause of many problems in Java programs now this nullpointer exception is a class that is declared in this package java. l [02:13] so an exception is an object that contains information about an error in this case this object is an instance of the null pointer exception class now we have several exception classes in Java and you'll learn about them as we go [02:26] through the Section now let's see where this exception occurred in our program we got this exception in the say hello method on line n of this file if we click we can go to the offending line so this happened when we tried to call the [02:41] two uppercase method a null that is why we got a null pointer exception now how did we get here we got here from the show method on this line okay but how [02:53] did we get to the show method we got here from the main method so this information that we have here is called the stack trace it shows the methods order and this is very useful when troubleshooting problems we can see [03:07] exactly how we got to the offending code now back to our say hello method when an exception occurs in a method we say that method through an exception just like how a person can throw a ball a method can throw an exception now when this [03:22] happens the Java run time looks for a block of code in that method for handling that exception we refer to that as an exception Handler in this implementation we don't have any exception handling code I'll show you [03:34] how to add that later so the Java runtime looks for an exception Handler in this method if it doesn't find it it goes to the previous method that is the show method here again we don't have any exception handling code here so the Java [03:48] runtime goes back to the main method hoping to find an exception Handler we don't have one here so that is why the Java runtime terminates our program and displays the exception now now as a good Java developer you should prevent such [04:02] exceptions from happening or anticipate and handle them properly and that's what the next video we're going to talk about the different types of [04:18] exceptions in Java we have three types of exceptions checked exceptions unchecked exceptions also called runtime exceptions and errors a lot of people new to Java find this confusing so let me make it super simple for you checked [04:32] exceptions are exceptions that we developer should anticipate and handle properly for example let's say we want to read data from a file what if the file doesn't exist maybe it got deleted just before we tried to open it for [04:44] reading good developers always anticipate and handle these edge cases terminate our program we would better display a friendly message to the user saying hey that file doesn't exist now the good news is that the Java compiler [04:59] and forces us to handle these errors that is why they're called checked exceptions because they get checked at compile time let me show you let's create a new file reader for reading data from a file so reader equals new [05:14] file reader let's say file.txt now look at this red underline the Java compiler knows that the Constructor of the file reader will throw an exception if the file doesn't exist so it's telling us [05:28] hey you haven't handled this EX exeption file not found exception this is an example of a checked exception so checked exceptions are exceptions that we should anticipate and recover from and that is why they're called checked [05:40] exceptions because the Java compiler checks them at compile time now the second type of exception is called unchecked exception or runtime exception as the name implies these exceptions are not checked by the compiler at compile [05:53] time they occur because of programming errors n pointer exception is an example in the last video we shouldn't have passed null to the say hello method this is a programming error so unlike checked exceptions we don't want to anticipate [06:08] and recover by displaying a friendly message like hey we made a mistake and tried to use an object reference with the null value doesn't make sense like this from happening in the first place how can we do that by good coding [06:22] practices and testing a lot of testing preferably automated testing that's a topic for an entirely different course now other examples of runtime exceptions are arithmetic exception this gets thrown if we try to divide a value by [06:36] zero we also have illegal argument exception for indicating that the argument we passed to a method was not accepted again this is a programming mistake not a kind of error that we should anticipate and validate another [06:49] runtime exception you may see is the index out of bounds exception which occurs if we try to access an element in an array or a string or a list using an invalid index for example we have five elements in an array but we try to [07:03] access the 10th element another popular runtime exception is ilal State exception which gets thrown if we try to call a method but the underlying object is not in the right state so these are runtime exceptions the third type of [07:17] exception we have in Java is an error which indicates an error external to our application examples are stack Overflow error or out of memory error so if the Java virtual machine runs out of memory there's nothing we can do about it so [07:31] just like runtime exceptions we should let the application crash rather than display a friendly message to the user we should try to identify the source of these errors these errors can happen because of programming errors like an [07:43] infinite recursion or for reasons outside of our application like a itself next we're going to look at the hierarchy of exception classes in Java [08:00] now let's look at the classes that represent different types of exceptions we have the throwable class which defines the common characteristics for all exceptions and errors like an error message and the stack Trace so every [08:14] kind of exception or error has an error message and a stack Trace below this class we have two classes exception and error the error class and all its subtypes represent errors that are external to our application like out of [08:28] memory error they exception class is the parent for all checked and unchecked exceptions below this class we have the runtime exception class which represents runtime or unchecked exceptions so if an exception class derives from the runtime [08:42] exception it's considered an unchecked exception otherwise it's a checked because we may think that any classes that derive from the exception class is a checked exception so runtime exception should also be a checked exception but [08:57] that's not how it works why honestly I have no clue you have to ask the developers of java so let's quickly explore this hierarchy in Java explore this hierarchy in Java documentation so we search for Java null [09:09] documentation so we search for Java null pointer oracle.com all right look at the exception hierarchy so here we have the not pointer exception this class derives [09:23] from the runtime exception which deres from the exception class which in turn derives from the throw able and as you can see the object class is the parent of all classes in Java now if you're curious what other runtime exceptions we [09:37] curious what other runtime exceptions we have you can go here and under direct known sub classes you can see all types of runtime exceptions now you don't really need to learn about each of these individually you will get to know them [09:50] as you build Java applications some of them may never occur to you so don't worry about learning all types of exceptions in Java next I'm going to exceptions in Java next I'm going to show you how to handle [10:06] exceptions now let's see how we can catch exceptions so let's create a file reader object reader we set it to a new file reader and here we type file.txt the name doesn't matter now right after this line we print a message like file [10:23] open now we have a compilation error because we haven't handled the file not found exception to do this we should wrap this code inside a tri block so we type try followed by curly braces to indicate a block of code then we move [10:39] indicate a block of code then we move these lines inside this Tri block now right after the tri block we type the catch clause and here in parenthesis we specify the type of exception we want to catch in this case File not found [10:53] exception then we give it a name by convention we call this object X as in short for exception so this x object is an instance of the file not found exception it's an object that contains information about this exception so here [11:10] we add another block and in this block we print a friendly message to the user we print a friendly message to the user something like file does not exist now something like file does not exist now let's run the [11:25] the proper way to handle checked exceptions now we can also get the message from this exception object so we type x. getet message this returns a [11:37] string so we can print it another the terminal file.txt no such file or directory this error message is defined in the file not found exception class okay now what happened to this statement over here we [11:53] tried to print file open but we are not seeing that message here's the reason when the line throws an exception the control moves to the catch block for that exception so the code that we have after the offending line will not be [12:09] executed however if I take this line and put it after our Tri catch put it after our Tri catch block it will get executed take a look so now we have file open so this is how we can catch [12:24] exceptions in Java now let me show you a trick I'm going to take this line out of trick I'm going to take this line out of our Tri block put it over here and then delete the rest of this code so let's say you're creating a file reader object [12:37] and the compiler is complaining that we haven't handled this checked exception now we don't have to manually type A TR catch block we can put the carrot over catch block we can put the carrot over here press alt and enter and select [12:50] surround with TR catch isn't that beautiful so intellig automatically created this Tri catch block for us now here we're calling the print stack Trace method of this exception object this will show us [13:04] something like what you saw before so we got an exception of type file not found exception here's the error associated with this exception now look at the stack trace this exception was thrown from the file input stream [13:18] class this is not part of our project this is part of the standard Java Library so in our show method when we try to create a new file reader the constru structor of the file reader was called and then internally this class [13:32] works with another class called file input stream here we have a few method calls and this is where the exception was thrown so sometimes you see a long stack Trace because of the method calls in the Java standard library or other [13:47] libraries that you use next we're going to talk about catching multiple types of to talk about catching multiple types of exceptions [13:59] sometimes we need to catch multiple types of exceptions for example after types of exceptions for example after reading a file let's call reader. read this reads one character and returns its numeric value so let's store it in a [14:12] variable called value now here we have another compilation error because we haven't handled the io exception so this read method May throw an IO exception if it cannot read data from this file to solve this problem we need to type [14:27] another catch Clause here so catch right here we want to catch an iio exception we give it a name and in this block we can print a message like could not read data the exception is gone now we have [14:44] multiple catch blocks and each cat block targets a specific type of exception so only one of these will be executed in this case we try to open a file that doesn't exist so this line will throw a file not found exception [15:01] and this catch block will catch that exception now the code inside this catch block will get executed and after that the control will move over here so this second catch block will get ignored okay so we have multiple catch blocks and [15:16] each catch block targets a specific type of exception now does the order of these of exception now does the order of these catch blocks matter sometimes it does so if I move this cat block over here you see a comp compation error the Java [15:30] compiler is saying that we have already caught the F not found exception what does this mean well let's look at the documentation for the file not found documentation for the file not found exception class so we type Java file not [15:43] exception class so we type Java file not found exception here it is okay so this class extends the io exception class and that means if we have a cach class for an IO exception we [15:58] this find not found exception this is the polymorphism principle of objectoriented programming we talked about this in the second part of this course let me show you if I have a variable of type IO exception let's [16:12] call it X I can set this variable to a new instance of IO exception or any classes that extend the io exception class so we can set this to a new file not found exception this is polymorphism an object [16:28] exception this is polymorphism an object may take take different forms so if you have a catch Clause to catch an IO exception this catch Clause can catch an IO exception or any of its derivatives any classes that extend the io exception [16:42] class okay now sometimes we want to treat these exceptions the same way for example here we can display a generic error message but other times we want to handle them differently if that is the case then we need to bring back this [16:57] catch clause and put it before for the first catch Clause so now if we get a file not found exception we can print a message like file does not exist so we giving the user a more specific error message okay now as [17:14] another example let's create a new simple date format object and call the method now here we have another compilation error because this parse [17:26] method May throw an exception of type Ty parse exception now we can put the car over here press alt and enter and have intellig add a catch clause for us there you go so it's right here now we have three catch Clauses [17:43] let's say we want to treat all of these the same way so first we can get rid of the file not found exception now we have two catch Clauses we can combine these using a vertical bar so right after IO exception we type a vertical bar then we [17:58] type parse exception and with this we don't need the second catch Clause so this block can catch exceptions of type IO exception or parse [18:10] exception so these are different ways to catch multiple exceptions the approach application and its requirements next we're going to talk about the finally [18:27] block let's say imagine this file exists so we successfully open it for reading but something goes wrong when we try to read data from this file this could happen because of a hardware problem now we have a problem in this code the [18:40] problem is that we have opened this file for reading but nowhere we have closed it file handles are operating system resources so whenever we get them we should always release them otherwise other processes may not be able to [18:54] access these resources so somewhere in this code we should write reader. close now there is a problem with this implementation can you tell the problem is that if this line throws an exception the runtime will pass the [19:10] control to this catch block so this line will never get executed now what if we put this line after our TR catch block now the reader variable is not recognized because we have declared it inside this Tri block so it's only [19:25] accessible in this block but let's not worry about it for a second the problem with this implementation is that sometime in the future another developer might come here and write some extra code and this code May throw an [19:38] exception again our reader is not going to get closed the proper way to handle these kind of scenarios is to use the finally block so right after the catch block we type finally now in this block we can release [19:53] external resources like file handles database connections network connections and so on so here we should typee reader. close but once again reader is [20:05] not recognized because it's only accessible in the tri block to solve this problem we need to declare this before our Tri block so we type file reader reader and then set it over here and by [20:21] the way we cannot use VAR over here because we can use VAR only when we set this to a new instance of a class so the compiler knows that this object is an instance of the file reader class in this case we're not initializing this [20:36] variable so the compiler doesn't know what is the type of this variable okay what is the type of this variable okay so let's type file reader now we have a compilation error variable reader might not have been initialized because in [20:50] Java before we can access an object we should always initialize it so if this line doesn't get executed if it throws an exception we'll try to use an uninitialized object to solve this problem we need to [21:05] explicitly set this to null the compilation error is gone now we have a different kind of error we'll talk about that in a second but first let's add an if statement we want to call the close method only if the reader is not null so [21:19] method only if the reader is not null so if reader is not null then close it but what is this compilation error onh handle exception IO exception so the close method may also throw an IO exception to solve this problem we need [21:34] to wrap this inside the tri catch block so we put the car over here press alt and enter and then surround with TR catch so here's the final result now [21:48] admit that we have a much better exception handling structure in C now that aside what I want you to take away here is that this final block will always get executed whether we have an exception or not if we don't have an [22:03] exception all the code inside the tri block will get executed and then the runter will pass control to the final block if one of these lines throws an exception one of our catch blocks will get executed and then the finally block [22:19] will get executed so the finally block will always get executed no matter what now this implementation is really ugly in the next video I'm going to show you in the next video I'm going to show you a better way to release external [22:36] this video as I said this video is part of my ultimate Java Mastery course that teaches you everything you need to know about Java from the basics to more learn more I highly encourage you to take the full course it's much faster [22:49] than jumping from one tutorial to another if you're interested the link is below this video thank you and have a great day