1 / 58

Java Exceptions: Handling Errors and Recovery

Learn about exceptions in Java, how they are thrown, and how to handle and recover from errors. Understand the flow of try and catch blocks, the use of the throws keyword, and the advantages of using exceptions in error handling.

darrelll
Download Presentation

Java Exceptions: Handling Errors and Recovery

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  2. Lecture 17 and 18 Exceptions – when it all goes wrong

  3. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  4. ArrayIndexOutOfBoundsException • You’ve probably come across those a fair amount • But what is an exception • What is this throwing business

  5. Exceptions • An Exception is an object • The java tutorials say: • The term exception is shorthand for the phrase "exceptional event." • An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. • Methods in Java use Exceptions to tell calling code • “Something went wrong boss. I failed”

  6. When an error occurs in a method, the method creates an exception object and hands it off to the runtime system. • The exception object contains; • information about the error • Error type • state of the program when the error occurred. • Creating an exception object and handing it to the runtime system is called throwing an exception. http://java.sun.com/docs/books/tutorial/essential/exceptions

  7. What could go wrong? • Trying to open a file on the computer that isn’t there • Trying to access more indexes than an array has • Trying to cast incompatible types • And many other situations....

  8. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  9. From Java tutorials (look them up!) • readFile (){ • open the file; • determine its size; • allocate that much memory; • read the file into memory; • close the file; } http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

  10. But... • What happens if the file can't be opened? • What happens if the length of the file can't be determined? • What happens if enough memory can't be allocated? • What happens if the read fails? • What happens if the file can't be closed? http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

  11. Using if • It sounds like we’re saying: • If this goes wrong (or if this file isn’t there){ Do this recovery code } • So why can’t I just use if statements? • The Java tutorials have a good explanation

  12. Error handling with if errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

  13. Error Handling with exceptions readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Pseudocode http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html

  14. Using exceptions means you can separate the error handling code from the functional code

  15. Another pro for exceptions • Using if statements normally means you will return a “special value” (if 0 is returned then everything went okay etc) • A special return value can potentially (accidently?) be ignored

  16. It is (almost) impossible for an exception to be ignored • Failure to handle an exception will result in termination of the program • Let’s look at a real usage – how do we find a risky method (one that is liable to throw an exception)?

  17. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  18. You can tell if a method will possibly throw an exception by the throws keyword

  19. FileReader • The FileReader object will read text files line by line and hand them to you as Strings • It is constructed with a file name in the brackets • If the constructor can’t find the file (the file must be in the same folder as the class file) it will throw an exception

  20. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  21. Try and catch • We try something risky • And catch any problems that occur • In java we use a try catch block

  22. Try Catch Block • So we wrap the code calling the constructor FileReader fr; fr = new FileReader(“myfile.txt”); In a try-catch block: FileReader fr; try{ fr = new FileReader(“myfile.txt”); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); }

  23. Exceptions • An FileNotFoundException is an object • That subclasses Exception • The catch argument declares an FileNotFoundException and calls it “ex” catch(FileNotFoundException ex){ • This is just like declaring any other argument

  24. You can then call helpful methods from the exception class like: • ex.printStackTrace(); • This effectively prints a list of what method threw the exception, what method called that method, what method called that one...... all the way back to main • We’ll talk about the stack later on in the lecture

  25. Go with the flow Program Control • How does a try catch block work? FileReader fr; try{ fr = new FileReader(“myfile.txt”); char myChar = fr.read(); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); } If this works... ...this is never run

  26. Go with the flow Program Control • How does a try catch block work? FileReader fr; try{ fr = new FileReader(“myfile.txt”); char myChar = fr.read(); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); } If this doesn’t work... This is not reached ...this is run

  27. Bigger Blocks • Methods can throw more than one type of exception: Method from ArrayList

  28. Catching multiple Exceptions try{ readThisTextDocument(thisFile); }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }

  29. Where to catch • The JVM will check each catch block in turn from top to bottom try{ readThisTextDocument(); }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }

  30. Polymorphic • Exceptions are polymorphic • If you catch a super class exception at the top, the JVM won’t keep checking for a more specific one try{ readThisTextDocument(); }catch(Exception e){ //Everything caught here }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }

  31. Finally • There is an optional ‘finally’ clause for a try catch block: FileReader fr; try{ fr = new FileReader(“myfile.txt”); char myChar = fr.read(); }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); }finally{ System.out.println(“Do this anyway”); } System.out.println(myChar); This is mostly used to free up resources. You probably won’t use it often

  32. Try catch is for exceptional circumstances • External things that you can’t control • Not for flaws in your code

  33. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  34. A fictional system public Car{ public void go() throws NoFuelException{ if(fuel==0){ throw new NoFuelException(); } } } Car void go() throws NoFuelException public Person{ public void drive(Car c){ c.go() } } Person void drive()

  35. How it works • The exception is always thrown back to the caller Throws an exception back Car Person Calls risky method Something goes wrong! No Fuel

  36. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  37. The exception hierarchy • There are many subclasses of exception..... • AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException, DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException, InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException, InvocationTargetException, IOException, JMException, LastOwnerException, LineUnavailableException, MidiUnavailableException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ServerNotActiveException, SQLException, TimeoutException, TooManyListenersException, TransformerException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URISyntaxException, UserException, XAException, XMLParseException, XPathException

  38. What the compiler checks • Exceptions can be broadly categorised into • Checked exceptions • Unchecked exceptions • When you call a method that could throw a checked exception, the compiler makes you handle it. You can either catch it, or defer it. We’ll cover deferring later.

  39. What the compiler doesn’t check • All subclasses of RuntimeException are Unchecked exceptions • The compiler can’t guess what state the program is going to get into or what data it’ll get fed so it can’t check for runtime exceptions

  40. What the compiler doesn’t check • Runtime exceptions include • ClassCastException • IndexOutOfBoundsException, • NegativeArraySizeException • NullPointerException • These are the exceptions you’ve probably seen. This is why you have never had to catch exceptions before

  41. Checked and Unchecked • Checked exceptions are likely to happen, and are out of your control, a broken drive, a network outage... • An Unchecked exception occurrence is your fault! • Perfect code should never throw an unchecked exception

  42. Unchecked Exceptions • Unchecked exceptions are normally thrown due to: • Logic error in the code • Undefensive programming – not making sure that your user has entered a number rather than a letter etc • Checking user input is sensible is called sanitising inputs

  43. What happens? • When any exception is thrown • The throwing method terminates immediately • The program does not run the rest of the method body • So methods that should return a value don’t have to return anything if they throw an exception

  44. Coming up • Exceptions • An Example • The Throws keyword • Try and Catch • The flow • Multiple exceptions • Finally • How exceptions are thrown • What the complier checks • Handle or Defer • Recovery • Writing your own

  45. Handling • There are two ways to handle an exception • deal with it here and now with a try catch block • defer it, pass it to another method to fix • This means passing it on to the method that called your methodthat called the methodthat threw the exception

  46. Defer it • What if Your class doesn’t want to deal with it? • Defer it! Throw it on to the method that called yours • Again? Throws an exception back Risky class Class that called your class Your class Calls risky method Something goes wrong!

  47. Class that called that Class that called that Class that called that

  48. If you don’t catch your exception by the time it is thrown back to the JVM, your program will terminate Class containing main() Class that called that JVM

  49. An exception doesn’t need to be passed from class to class, it can be passed between methods in the same class Method that called that Method that called that Method that called that

More Related