Java for Network Engineers 28 Hello Exceptions

Show video

I mentioned exception handling earlier  as another way of managing flow control   um exceptions are basically a way of handling  errors of handling exceptional conditions in your   code there used to be quite a heavy performance  cost for exceptions that's not so much the case   anymore um but you so you don't have to be wary  of using exceptions rather than say returning null   um they're basically just another  tool in the toolkit for managing input   um exceptions come about where you know the option  is perhaps say you're connecting to a database and   you want to return an open database handle so  you can run statements and inquire some data   what should happen if you try to connect  to the database and nothing happens or   what should happen if you try to write a  file and the file already exists or you   don't have permission to write the file in the  directory where your program wants to write it   um the program has to handle that condition that  failure in C what you would probably do or many of   the languages is you would return a null value  or you'd return some error condition and hope   that the user checks the air condition before  proceeding so if you're supposed to return say   a database connection object the user would  look at that object see if it's a null value   which would indicate an error or see if it's  a instantiated object if it's instantiated   great continue if it's null perhaps displayed  in error you can do that in Java as we saw   earlier it's possible to program exactly that  way check whether a value has a non-null value   and continue otherwise take some other action  but the more idiomatic way to handle that kind   of situation in Java is to throw an exception  and to force the caller to catch that exception   so basically an exception interrupts the regular  flow of the program and Bubbles up through the   call stack until it's caught so the basic  code for exception handling looks like this   rather than say like we saw if Clauses earlier  wrapping a block of curly braces to write code   with exception handling you use what's called a  try block so you have the keyword try followed   by curly braces and then you have a catch  Clause followed by an exception and then   um a definition of a type of exception to catch  in this case in this example here exception   the with a capital E is the grandparent of all  exception classes so this code would basically   catch any exception no matter what kind of thing  it was whether it was a file not found exception   or you don't have permission to write that file  here exception or and I couldn't write to the   database exception any kind of condition would  be caught by this by this catch block so it's   it's typically considered bad form to catch  the catch the the top level exception except   perhaps maybe in your main block you would  use a try and then catch the the exception   class so you could elegantly handle exiting from  your program but typically in your code you're   going to have much more specialized cases that  inherit from exceptions somewhere down the line   and so you can handle individual cases  more specifically there are basically two   kinds of exceptions they're what are called  checked exceptions and unchecked exceptions   um checked exceptions are those that can be  determined at compile time and that you might   expect your application to recover from unchecked  exceptions are runtime errors often stemming from   Bad data where an application can't reasonably be  expected to recover so in the case of a database   failure that would be a checked exception and the  function that wants to connect or the method that   wants to connect to the database would have  to declare that it's going to throw you know   a connection failure exception or a database not  found exception or however you want to represent   that the the connection method would have to  declare that it throws a particular kind of   exception and then the code that calls that method  to connect to the database would have to have   a catch block that catches that particular kind  of exception or it would have to throw it itself   unchecked sections are things more like runtime  errors like you expected to have an array   with five elements and you tried to access the  Sixth Element or something like that where it's   um it's a runtime error probably stemming from Bad   data or something like that and that you  can't necessarily expect to recover from so a method has to declare its checked exceptions  um exceptions can be caught as I was just saying   or they can be thrown up the stack what that  means is if you have a function Foo that calls   bar that calls bat and bat throws a checked  exception bar would have to either catch it   and handle it or it would have to declare  that it throws that exception as well and   then it throws that exception as well so  again we can write some sample code here we have some exceptions I don't think I have  anything written all right so let's just write um we can do something simple here where um this  will just be a silly example but let's say let's wrap this in a try block and say if args.length equals zero we're going to throw an exception and now we don't have to have this test here  because we're essentially handling it above there and what we'll see here in our catch block is that we can catch that exception and we're going to say eat a message which  will grab that string that we're passing in   up here so it's going to happen if we  run this code with no arguments is that   this for Loop will never be executed  so if we run it the way we have been say hello and we say hi to Mom and Dad that runs  fine but now what's going to happen is that that   while that for Loop is that would give us an  error before if we tried to iterate over it   um here we're just gonna catch that exception and  that whole block is going to get entirely skipped   so any code that we we wrote here so if we had you  know other code here um you know say we wanted to let's say hello this is gonna the this  block would this for Loop would never have   um executed in any way because  there weren't any arguments   um but in this case uh this code would be let's  say hello but again we're not going to see it because we don't have anything um we don't have  any arguments and the exception the exception   is being thrown before that block if we add  those back in you can see let's say hello   is in fact being executed uh we'll we'll see exceptions later on as we  get into some of the more advanced programs but   exception handling is a big part of how Java  manages the flow of control in an application   we were talking a bit about uh exceptions and  we're going to move on to uh data structures   but I wanted to touch on a few more things about  exceptions first uh because I think an example   will help with some uh some of those Concepts  might not have been clear particularly in terms   of the notion of an exception hierarchy I  also wanted to talk about the final clause   which is something I forgot to talk about  when I was talking about try and catch so   let's start with an example here of um in  this example we'll cover what an exception   hierarchy is and how you can catch exceptions  at different levels and throw them at different   levels and decide where you want to deal with  an exception so if we look in this directory   I've got a couple of simple uh exception classes  here that don't really do anything but just for   the purpose of creating an exception hierarchy  they'll demonstrate the concept so we have the   instructor exception and the student exception  and then we have this other preparedness   exception they're all very simple all they do  is extend exception preparedness extends it   directly and then if we look at the instructor  exception it extends the preparedness exception   and the student exception does the same thing  so we have two classes student exception and   instructor exception they both extend preparedness  exception which itself extends exception which is   the root cause so let's write a simple class that  uses these okay so we have a sim a very simple   class here uh that basically creates a new object  and then calls a couple of methods on those teach   class and submit homework when we call teach class  we get a line study the books when we call submit   homework let me get a line here's my book report  so let's compile this let's save it and compile it instead of the books here's my book report pretty  simple all right what happens though if say our   students are unprepared instead  of saying here's my book report   let's have them throw an exception  throw new student exception my dog ate my book report so now it happens when you try to compile  this here this is going to fail because the   student exception is being thrown but we're not  declaring that it was thrown so it's saying the   reason here the actual informal argument lists  differ the problem is that we're throwing an   exception that we're not declaring here we  can say that this throws a student exception now I'll get us part way out of the woods but  now we're going to get another error um exception that should work um then we got to catch it up here and down here we're going to catch our student exception I'm going to print that out and so now our main method is catching  this exception that is thrown down here oops Insurance required no arguments oh we don't   have a no argument Constructor for  our student exception I guess we   have to edit our exceptions a little bit  here so let's edit the student exception uh uh a public students and we can call the superclass we'll do the same thing here   so this is just calling the instructor  the uh Constructor and the superclass where this is now going to be a  preparedness exception [Music] it does that and now we have to do the same thing for  the instructor exception [Music] oops and I believe now we're out of the woods  so now we've got all that stuff compiled   we can run our example again and we see  the instructor teaching and instead of   seeing we actually don't have to comment that  out let's leave this let's throw the exception um this should probably be a compiler  because it's going to tell us that we   can never get to this line but let's try and see yeah so let's say uh we're just going to trick  the compiler into thinking   that it has the option of not executing this code Okay so we've got a condition if condition and again I don't need these braces around  this but it's just so much nicer for our   code maintenance if we have them all right  so if the condition is true then we'll throw   an exception so what we're going to see  here is that we're trying to teach the   class and submit the homework teach class  will complete but we're never going to get   down to submitting this homework because  we're going to throw that exception first which is exactly what we see here's the output  from teach the class and then we don't see the   output from complete submit the homework we're  just saying uh oh my dog and my book report which   is what we're seeing down here that's the  uh title that we sent to that exception now   here we're declaring that we um through  a student exception if we remove that   declaration and try to compile we'll see um  that that'll fail because we're throwing an   unreported exception because student exception is  in fact a checked exception because the exception   extends the exception class that means that it's  a checked exception if we wanted to instead throw   an error which would be an unset unchecked  exception we would extend the error class   but here we are throwing the student exception  which is checked if we change this to error that'll compile it's telling us that  student exception has never thrown and   that's because in this case we're getting an error from the main method saying that  student exception is never thrown and so even though we're declaring or we're throwing we were you  know deciding to throw this   error down here because that's a runtime  exception uh the compiler's letting us   compile it and we'll still see that  we get the error if we actually run it   but it's not very nicely handled and so  let's change this back to the throws student exception and let's make this into a student exception too okay um all right so that handles  the student exception what happens   if there's a failure teaching the class   instead of submitting our homework for the class  we can instead throw an instructor exception and we'll have to do the same thing  here declare that we're throwing it now if we try to compile this again we'll  get an error because here we either need an   airport exceptions we need to um did we say  they were a throwing an instructor exception   online oh yeah line eight that's up in Maine  so here it's saying that teach class is   um potentially throwing an instructor  exception but we're not handling it   so we can essentially duplicate our method  here let's catch the instructor message to this will now compile but it's kind of a waste if we're  doing exactly the same thing with   both our students our student exception  and our instructor exception if you   recall those both inherit from a common  preparedness exception so let's change   this instead of catching the student  exception and the instructor exception   let's replace this with a single preparedness  exception which both of those descend from and then we don't know we don't need  these here so let's comment those out compile this again and you can see exactly the same thing happens but   let's do something else here let's uncomment these  change the output a little and you'll see that the   order of the catch blocks matters basically  exceptions are caught from most specific to   least specific so student exception and instructor  exception are both more specific than preparedness   exception so we can say let's change this to  Ono says the student oh no says the instructor and then just oh no for our general  preparedness if we execute this what   we're actually going to see is Ono says the  instructor because the instructor exception   is the most specific case and it's listed  in front of the preparedness exception and it's telling us that we can't get to the  preparedness exception in this case because   um nothing else is throwing it uh let's change  if we change this to um throw a preparedness then that should let us compile and again we're getting to Ono says the instructor   so even though we are catching the preparedness  exception down here because in it the instructor   exception is an instance of preparedness exception  because it's more specific it's being caught first similarly down here um there's you might notice  the disconnect between preparedness exception   and student exception this is just fine because  all student exceptions are because they extend   preparedness exception we can declare that  we throw the more generic thing and the right   thing still happens there um so here let's leave  this as just catching our preparedness exception   I want to show one more thing that's important to  note about try catch Clauses which is the finally   block the finally block um is a block of code  that will always be executed even if there is   an exception so for example here teach class is  going to throw an exception it's going to say oh   my dog ate my lecture notes um but what we want  to do is uh let's write on the Whiteboard anyway we always want to write  something on the right board we'll write hello world so it's going to happen here even though we're  throwing an exception from teach class so we're   never getting down to submit homework we're  still always going to execute this final clause which you can see here my dog ate my election  notes but I'm still able to say hello world so   why is that important that's important for example  if we go back to the database example that we were   talking about earlier imagine this time instead  of having a problem where the database failed to   connect that there was some kind of a failure  parsing the data so we go we get a connection   we run a couple of statements we're retrieving  some data and then something explodes that we   need to deal with and it's catastrophic and so the  system needs to quit in that case we want to quit   but perhaps we also want to close the statement  handle or close the connection to the database   or close the connection to a server or whatever  it is that we've done we want to take care of our   resources before just exiting the system we would  put those statements that wrap up our resources   that were in use when the exception occurred into  this finally block to ensure that the methods on   that finally block or the methods that deal with  cleaning up those resources are always executed so   the finally block is a is an important concept  um because it basically gives you a chance to   clean up any resources that are in use uh when  the above uh trike block throws an exception   all right uh that's pretty  much it for exception handling

2023-02-22

Show video