Presentation is loading. Please wait.

Presentation is loading. Please wait.

Coming up Exceptions An Example The Throws keyword Try and Catch

Similar presentations


Presentation on theme: "Coming up Exceptions An Example The Throws keyword Try and Catch"— 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 Exceptions – when it all goes wrong
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 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.

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; }

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?

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; errorCode = -3; close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } errorCode = -5; return errorCode;

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) { } catch (memoryAllocationFailed) { } catch (readFailed) { } catch (fileCloseFailed) { } Pseudocode

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

21 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

22 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

23 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!”); }

24 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

25 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

26 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

27 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

28 Bigger Blocks Methods can throw more than one type of exception:
Method from ArrayList

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

30 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 }

31 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 }

32 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

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

34 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

35 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()

36 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

37 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

38 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

39 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.

40 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

41 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

42 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

43 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

44 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

45 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

46 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

47 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!

48 Class that called that Class that called that Class that called that

49 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

50 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

51 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() }

52 The Stack It’s time to look at the stack Now Eric talks

53 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

54 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

55 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;

56 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

57 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

58 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


Download ppt "Coming up Exceptions An Example The Throws keyword Try and Catch"

Similar presentations


Ads by Google