1 / 41

F21SF Software Engineering Foundations

Dept of Computer Science. F21SF Software Engineering Foundations. L09 Input, Output and Exceptions. Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision. I/O. So far we have used Standard output and not asked for any input at all.

Download Presentation

F21SF Software Engineering Foundations

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. Dept of Computer Science F21SFSoftware Engineering Foundations L09 Input, Output and Exceptions Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision SJF L11

  2. I/O • So far we have used Standard output and not asked for any input at all. • Standard input and output is not really suitable for a real application • Use a dialog box or more sophisticated graphical user interface – covered in a week or two • With some sort of data storage • This course – text files • Real life – text files, xml formatted files (text files with html-like tags to describe the content), binary files (data stored as objects – must be created by a program), or a database • Once we start using input, we have to consider validation and errors SJF L11

  3. Topics and code • Exceptions • Checked and unchecked exceptions • Exception handling • Multiple exceptions • Reading and writing from a text file • Writing to a text file • Reading from a text file using the scanner class • Getting a line • Handling a comma separated line • Checking for errors in input data • Code - SEF11.zip SJF L11

  4. Exception handling • So far our code has all assumed that everything is going to work as expected • All data is hard-coded into the program • If it is in the wrong format, the program will not compile, may crash or produce incorrect output • Reading from file, and writing to file, are very error-prone procedures • The types of problem discussed today are: • File not found • What you read from a file is not what you wanted (e.g. text instead of an integer, missing items) SJF L11

  5. Exceptions • We have already met some ‘unchecked’ exceptions • java.lang.ArrayIndexOutOfBoundsException • java.lang.NullPointerException • The program crashes and prints a stack trace • There are many more exceptions! • In this lecture, you will learn to write code to handle exceptions. SJF L11

  6. Stack Trace recap • This message is a Stack Trace, which includes • The type of exception • A message explaining the error • The class, method and line where the error occurred – this is likely to be a java class that you are using but did not write • The class, method and line in the class that called the above method – click on this in eclipse to highlight the line • The class, method and line in the class that called that method etc back to the main method Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at Name.getInitPeriodLast(Name.java:64) at TestName.main(TestName.java:10) SJF L11

  7. Exception handling • With these unchecked exceptions, you can decide what to do: • Do not consider the possibility of them occuring. Let the program crash, that’s ok because you are still developing the program and your code must be wrong. (e.g. null pointer exception means logic error in code) • Do some checks to ensure that the exception is not going to be thrown (e.g. range checks for array indexes) • Look out for the exception and take appropriate action if it happens • A real-life program should NEVER crash. It might have to stop with an error message, or maybe it can recover and continue. SJF L11

  8. Exception handling • Java also has some checked exceptions, which are so serious that the compiler forces the programmer to look out for them • This lecture explains how to look out for exceptions that you know might occur, whether they are checked or unchecked SJF L11

  9. Exception handling • We take this approach: • Assume the code will work – ‘try’ it out • ‘Catch’ an exception which might occur and handle it • Like this • Surround the code that you hope will work with a try block • At the end, place catch blocks naming the types of exception you are looking out for SJF L11

  10. A try/catch example try { ... //if ‘i’ is within range, name is created //if not, goes to the catch String name = parts[i]; Name myname = new Name(name); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Not enough items in the line " ); } //this line will be executed either at the end of the try or at the end of the catch System.out.println("The end"); SJF L11

  11. Paths through try/catch • So far we have either: • Everything is ok • All the code in the try block is executed • Skip over the catch blocks • Carry on with the program • An error occurs • The code in the try block is executed up until the exception occurs • Execution moves directly to the appropriate catch block – execute the code in the catch block • Then carry on with the code after all the catch blocks • If there wasn’t a matching catch block for the exception, the program would crash, printing a stack trace and exiting. SJF L11

  12. Catching an exception • When you catch an exception, you have several choices, depending on the situation: • Display a user friendly message of your choice • Display a message including information from the Exception object getMessage() method • Display the stack trace – the state of the program when the crash occurs, plus the reason. There are methods to • Return the stack trace as a String • Print the Stack trace to System.out • When you have displayed what you like, you can either continue with the program, or stop. • System.exit(0) is used for a normal stop • System.exit(1) is used for an ‘emergency’ stop SJF L11

  13. Exception-throwing principles • A special language feature. • No ‘special’ return value needed to say whether a method worked or not • Errors cannot be ignored. • The normal flow-of-control is interrupted. • Specific recovery actions are encouraged. SJF L11

  14. Input-output and text files • Input-output is particularly error-prone. • It involves interaction with the external environment. • Errors like ‘file not found’ are quite likely to occur, either through a naming error, a path error, or trying to read using a failed network • I/O errors are therefore checked exceptions • The programmer MUST write a try/catch • It doesn’t matter what the programmer does, but they must show that they have considered the possibility of error and written some code accordingly. SJF L11

  15. Readers, writers, streams • The java.io package supports input-output. • java.io.IOException is a checked exception • IOException has subclasses FileNotFoundException and many others • Readers and writers deal with textual input. • Based around the char type. We will just look at this. • Streams deal with binary data. • Based around thebyte type. Complete objects can be written to and read from file. Not covered in this course, but useful for saving objects between one program run and the next. SJF L11

  16. List of Students • We extend the List of Students example to cover • populating the list from a text file • writing the list to a text file • We have added reading and writing methods to the StudentList class • Some professionals consider that it is better to have all the I/O in a separate class. Then the StudentList class could be used in another program which isn’t using these text files, maybe using a different input format. • However, we don’t plan to reuse this class, and the i/o is related to the list of students. • Lecturers have argued in corridors about this design issue! SJF L11

  17. Writing • We look at writing first because it is more straightforward • In these examples, a text report is first created and then written to a text file. It is a suitable approach for this course. • In other situations, you might want to open the file at the start of the program, add text from time to time, and finally close the program. SJF L11

  18. Text output to file - Strings • Use an object of the FileWriter class with the write method to print Strings • Open a file. • Write to the file. Using the write method, the parameter must be text and if you need any newlines they must be included in the text (“\n”) • Close the file. Essential to ensure that the last items are output to the file and not held in memory waiting to be written. • Failure at any point results in an IOException so a try/catch block should be used SJF L11

  19. Ending the program • If the error is ‘file not found’, you can either stop or try to recover by asking user to enter another name, or by pausing and trying again in case of temporary network problems • In this course, we’ll print a message and stop. • The example code in StudentList.java shows a user-friendly message if FileNotFound occurs, but stops with an error if anything else happens. SJF L11

  20. A general filewriting method public void writeFile(String filename, String text) { FileWriter fw; try { fw = new FileWriter(filename); fw.write(text); fw.close(); } //message and stop if file not found catch (FileNotFoundException fnf){ System.out.println(filename + " not found "); System.exit(0); } //stack trace here because we don't expect to come here catch (IOException ioe){ ioe.printStackTrace(); //goes to standard output System.exit(1); } } SJF L11

  21. Catching multiple exceptions • If multiple catch clauses are declared, each catch is examined in order until the first one is found that matches • By being the exact type or a supertype of the exception that occurred • FileNotFoundException is more specific than IOException, so must come first try { ... } catch(EOFException e) { // Take action on an end-of-file exception. } catch(FileNotFoundException e) { // Take action on a file-not-found exception. } catch(IOException e) { // Any other I/o problems } SJF L11

  22. Text output to file – using print method • Use the PrintWriter class (created from a FileWriter object) with the print/println methods to print formatted output (anything other than Strings), used in the same way as System.out.println FileWriter fw = new FileWriter("myfile"); PrintWriter pw = new PrintWriter(fw); pw.print(5); pw.println(" is the number 5"); SJF L11

  23. Text input from file • Several possibilities • Use the Scanner class in java.util, instantiated with the File class. Use methods such as nextLine, nextInt, hasNextLine. Today’s example uses this approach, just using nextLine. • Use the FileReader class • augmented with BufferedReader for line-based input. • Similar, a later example uses this • alone to read character by character SJF L11

  24. Input data • The data is stored in a comma-separated text file • 0011,Helen Scott,1,MIC,ARA • This is a simple way of entering bulk data • Algorithm for reading the file: • Until there are no more lines Each line is read Each line is processed • Algorithm for processing the line: The data is extracted, A new Student object is created, The Student object is added to the list. SJF L11

  25. Text input from file - Scanner • This example shows how to get each line from a text file. • Once you have the line, you can process it however you like File f = new File("Myfile.txt"); Scanner scanner = new Scanner(f); while (scanner.hasNextLine()) { String inputLine = scanner.nextLine(); //do something with this line processLine(inputLine); } SJF L11

  26. UML sequence diagram – internal method calls main() sl: StudentList Create studentlist Read file process line S:Student add Not all methods shown. F21SF SEF L2

  27. Private methods • The processLine method is private, because it is only used within this class • It should not be used by other classes • Putting the process line code into a separate method makes the readFile and the processFile methods relatively short and easier to understand. • The readFile method can be used without alteration for reading any set of lines SJF L11

  28. Splitting a comma separated line • Use the String split method to assign each comma-separated item into the elements of a String arrayString parts [] = inputLine.split(","); • For integers, use the static Integer.parseInt method which takes a String parameter and converts it to an integer. There is a similar method for double.String yearNum = parts[2]; yearNum = yearNum.trim(); //remove any spaces int year = Integer.parseInt(yearNum); SJF L11

  29. Copying an array • The qualifications are at the end of the line • We know what else should be in the line, so we can find out how many qualifications there are • The static java method System.arraycopy is used to copy the qualifications into an array of their own. You need the start position and the length. SJF L11

  30. Student example • Study the code in StudentList.java • An exception might occur if the data in the file is invalid. E.g. • if the line is incomplete, the array index e.g. parts[2] may be out of bounds. • If the year is not an integer, we get a number formatting error • If the name is empty or does not contain a space, the Name constructor will fail • If any other items are missing, the code will interpret the data incorrectly and may throw one of the above exceptions, another exception, or store incorrect values in another field. SJF L11

  31. Student example • This program has been written to catch some errors • A blank line is ignored • Using exceptions for number formatting and array index out of bounds • If a line contains an error, it displays a message , ignores that student, and continues. SJF L11

  32. Example of catch //this catches trying to convert a String to an integer catch (NumberFormatException nfe) { String error = "Number conversion error in '" + line + "' " + nfe.getMessage(); System.out.println(error); } //this catches missing items if only one or two items //other omissions will result in other errors catch (ArrayIndexOutOfBoundsException air) { String error = "Not enough items in : '" + line + "' index position : " + air.getMessage(); System.out.println(error); } SJF L11

  33. Errors in the input data • You could assume that the data in the file is formatted correctly. • You don’t catch any exceptions, except the checked FileNotFoundException • You publish your program stating that data is assumed to be correctly formatted. • The program may crash because of incorrect data. The data must be corrected and the program run again. • You could make some checks and produce user-friendly messages if the data is invalid • You check some values using ‘if’, to prevent exceptions occuring (e.g. check array index in range) • You catch some exceptions (e.g. array index out of range) • You don’t need to do both for indexes! SJF L11

  34. Error checking • Error-checking is VERY time-consuming • Both writing the code • And testing the code (check all possibilities) • It is very important to • Realise what sort of input errors your program is likely to encounter • Is data entered by a human or a machine? What type of errors might there be? Would you want to stop the program if the data is incorrect? • Specifiy which input errors your program can cope with (if any) • Don’t check for errors that won’t happen! • It is often a good idea to start by assuming that input data is always correct. Get that code working. Then add checks. SJF L11

  35. The finally clause • A finally clause is executed even if a return statement is executed in the try or catch clauses. • A uncaught or propagated exception still exits via the finally clause. try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or notan exception is thrown. } SJF L11

  36. File I/O Warnings • Remember the ‘newline’ characters • If your program doesn’t quite work, you may be ignoring these • Remember to close the file • To release resources • To ‘flush’ the last output from internal buffer to file • Ideally one should close the file in a finally block, to ensure that all resources are released whether the try is successful or not. • But closing the file might cause an exception, so you need another try/catch within the finally block. It starts getting very messy. • Use ‘finally’ in a real application, not essential for the coursework SJF L11

  37. Using Files with eclipse (1) • Add an input text file to eclipse by right-clicking on the project name, choose Import: File System and navigate to the input file. • If it appears as shown in the screenshot, you can refer to the text file in your code just with the filename. SJF L11

  38. Using Files with eclipse (2) • Once you’ve run a program which reads from a file and writes to a file – it looks as if nothing has happened! • The first time, right click on the project name and press Refresh • Then you will see the newly created text file, next to the input file. • You can look at this within eclipse by double-clicking on it. SJF L11

  39. Summary of the first part of the course • We have now covered simple object-oriented programming using classes for objects. We have • A main method to start things off • A manager/interface class • A class for a collection of objects • Classes for basic objects such as Car, Student • Also • Selection, Repetition • Primitive types, Strings, API methods • Static for constants and methods • Formatting • Integer division • Java arrays and ArrayLists • What can go wrong. Java exceptions. The debugger. • File reading and writing • Class and sequence diagrams • Style and comments SJF L11

  40. Summary of the second part • Use cases and activity diagrams • Designing and using objects with inheritance (share common features between classes) • Using a Graphical User Interface, using buttons, textfields, labels. • Getting data from the user and validating it • Displaying data in the GUI • Sorting lists in various orders, using the java Collection methods SJF L11

  41. To Do Now • Read through the lecture and the example code. • You can now complete Assignment One SJF L11

More Related