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
Exceptions – when it all goes wrong Lecture 17 and 18 Exceptions – when it all goes wrong
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
ArrayIndexOutOfBoundsException You’ve probably come across those a fair amount But what is an exception What is this throwing business
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”
The exception object contains; 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
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....
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
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
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
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
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; errorCode = -3; close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } errorCode = -5; return errorCode; http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html
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) { } catch (memoryAllocationFailed) { } catch (readFailed) { } catch (fileCloseFailed) { } Pseudocode http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html
Using exceptions means you can separate the error handling code from the functional code
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
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)?
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
You can tell if a method will possibly throw an exception by the throws keyword
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
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
Try and catch We try something risky In java we use a try catch block And catch any problems that occur In java we use a try catch block
Try Catch Block So we wrap the code calling the constructor FileReader fr; fr = new FileReader(“myfile.txt”); In a try-catch block: try{ }catch(FileNotFoundException ex){ System.out.println(“Ooops!”); }
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
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
Go with the flow How does a try catch block work? If this works... 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
Go with the flow How does a try catch block work? 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
Bigger Blocks Methods can throw more than one type of exception: Method from ArrayList
Catching multiple Exceptions try{ readThisTextDocument(thisFile); }catch(EOFException e){ //The end of the file }catch(FileNotFoundException e){ //The file isn’t there }
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 }
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 }
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
Try catch is for exceptional circumstances External things that you can’t control Not for flaws in your code
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
void go() throws NoFuelException 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()
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 The exception is always thrown back to the caller
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
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
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.
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
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
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
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
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
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
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 method that called the method that threw the exception
Class that called your class 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!
Class that called that Class that called that Class that called that
Class containing main() 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
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
Throwing public Car{ public void go() throws NoFuelException{ if(fuel==0){ throw new NoFuelException(); } How do I get a method to throw an exception that it has been thrown? Simple, you mark that method with the throws declaration public Person throws NoFuelException{ public void drive(Car c){ c.go() } public Person{ public void drive(Car c){ c.go() }
The Stack It’s time to look at the stack Now Eric talks
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
Recovering from an exception So you have an exception thrown You tell the user their file isn’t there You have handled the error What now? Often you can use a loop to try the task again
Attempting a no fuel recovery boolean successful = false; int attempts = 0; do { try { person.drive(myCar); successful = true; } catch(NoFuelException e) { System.out.println(“no fuel in the car!”); attempts++; } while(!successful && attempts < MAX_ATTEMPTS); if(!successful) { Report the problem and give up;
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
Writing your own You will probably spend more time catching other people’s exception than writing and throwing your own Subclass Exception for a checked exception Subclass RuntimeException for an unchecked exception
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