Week12

148 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
148
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Week12

  1. 1. Week 12Exceptions andFile I/O
  2. 2. Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act).The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act.Do not remove this notice.© 2004 Pearson Addison-Wesley. All rights reserved 10-2
  3. 3. Methods Return Values• We have seen that programs are usually broken into modules:  Classes provide a set of attributes that a collection of “things” have in common, even if they have different values  Methods provide access to class attributes  Methods also allow a large problem to be broken into several sub-task, and each method provides one sub-task• Methods are passed input parameters• Methods work on their inputs, possibly call other methods, and can return one value to their caller• But what do we do if there isnt a value to return?© 2004 Pearson Addison-Wesley. All rights reserved 10-3
  4. 4. Consider the Scanner Class• The Scanner Class reads input from the user.• Actually, it reads lines of text from somewhere, and converts the text into something else, e.g.  scan.nextInt() reads in the next integer from the line of input text• So, we can do this: System.out.print(“What is your age: ”); age= scan.nextInt();• What happens when the user types a word instead of a set of digits?• What int value will the nextInt() method return?  We cant use a specific int value to indicate error. Why not?© 2004 Pearson Addison-Wesley. All rights reserved 10-4
  5. 5. We Need Two Types of Return Values• We cant return a normal value to the caller of a method, yet we want them to know that something went wrong• Many languages, including Java, allow a method to return two types of things back to the caller:  A return value, which is what usually happens, or  An Exception, which informs the method caller that there is no return value, and something went wrong• A method can only send back one of these things, not both• A method caller can choose to receive either or both of these things, or ignore either or both too© 2004 Pearson Addison-Wesley. All rights reserved 10-5
  6. 6. Exceptions: Visually age= scan.nextInt(); nextInt() return(num); Throw Exception;© 2004 Pearson Addison-Wesley. All rights reserved 10-6
  7. 7. Exceptions• An exception is an object that describes an unusual or erroneous situation• Exceptions are thrown by a program, and may be caught and handled by another part of the program• A program can be separated into a normal execution flow and an exception execution flow• Java also has a related thing called an error• An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught© 2004 Pearson Addison-Wesley. All rights reserved 10-7
  8. 8. Exception Handling• Java has a predefined set of exceptions and errors that can occur during execution  And you can make your own up to suit your situation• A program can deal with an exception in one of three ways:  ignore it  handle it where it occurs  handle it an another place in the program• The manner in which an exception is processed is an important design consideration• Try to handle an exception where you can recover from it© 2004 Pearson Addison-Wesley. All rights reserved 10-8
  9. 9. Exception Handling • If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message • The message includes a call stack trace that:  indicates the line on which the exception occurred  shows the method call trail that lead to the attempted execution of the offending line© 2004 Pearson Addison-Wesley. All rights reserved 10-9
  10. 10. Ignoring an Exception System.out.print(“What is your age: ”); age= scan.nextInt(); What is your age: none of your business InputMismatchException: next item is not an integer at Scanner.nextInt() (program stops)© 2004 Pearson Addison-Wesley. All rights reserved 10-10
  11. 11. Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions© 2004 Pearson Addison-Wesley. All rights reserved 10-11
  12. 12. Catching Exceptions: The try Statement• To handle an exception in a program, the line that throws the exception is executed within a try block• A try block is followed by one or more catch clauses• Each catch clause has an associated exception type and is called an exception handler• When an exception occurs, processing continues at the first catch clause that matches the exception type© 2004 Pearson Addison-Wesley. All rights reserved 10-12
  13. 13. An Example try { System.out.print("What is your age: "); age= scan.nextInt(); } catch (InputMismatchException e) { System.out.println("You didnt type a number"); System.out.println("Java says: " + e); }• Note that e is an object declared as part of the catch line, and it is an object of the InputMismatchException class© 2004 Pearson Addison-Wesley. All rights reserved 10-13
  14. 14. Class Question try { System.out.print("What is your age: "); age= scan.nextInt(); } catch (InputMismatchException e) { System.out.println("You didnt type a number"); System.out.println("Java says: " + e); }• How do we modify the above so that it loops until the user does enter an integer value?© 2004 Pearson Addison-Wesley. All rights reserved 10-14
  15. 15. The finally Clause• A try statement can have an optional clause following the catch clauses, designated by the reserved word finally• The statements in the finally clause always are executed• If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete• If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete© 2004 Pearson Addison-Wesley. All rights reserved 10-15
  16. 16. Input/Output and Exceptions• Lets examine issues related to exceptions and I/O• A stream is a sequence of bytes that flow from a source to a destination• In a program, we read information from an input stream and write information to an output stream• A program can manage multiple streams simultaneously• Streams can be connected to the keyboard, the terminal, or to/from files on the computer, and even network connections© 2004 Pearson Addison-Wesley. All rights reserved 10-16
  17. 17. Standard I/O• There are three standard I/O streams:  standard output – defined by System.out  standard input – defined by System.in  standard error – defined by System.err• We use System.out when we execute println statements• System.out and System.err typically represent a particular window on the monitor screen• System.in typically represents keyboard input, which weve used many times with Scanner objects© 2004 Pearson Addison-Wesley. All rights reserved 10-17
  18. 18. The IOException Class• Operations performed by some I/O classes may throw an IOException  A file might not exist  Even if the file exists, a program may not be able to find it  The file might not contain the kind of data we expect© 2004 Pearson Addison-Wesley. All rights reserved 10-18
  19. 19. Writing Text Files• Java provides a whole pile of classes to deal with I/O. In fact, there’s a complex hierarchy of classes• We are going to look at how to get access to text files, in a way that allows you to use println() and friends• Text files are files made up entirely of plain text. They could be:  Plain text .txt files  Comma-separated value .csv files  Web documents , i.e. .html files© 2004 Pearson Addison-Wesley. All rights reserved 10-19
  20. 20. Writing Text Files• In order to use a text file, we must open it for writing. This gives us exclusive access to the file: PrintWriter outFile; String filename= “myfile.txt”; try { outFile= new PrintWriter( new BufferedWriter( new FileWriter(filename))); }© 2004 Pearson Addison-Wesley. All rights reserved 10-20
  21. 21. Writing Text Files• Opening a file can throw an IOException for many reasons, so we must try { … } catch{ … } it• Once the file is open, we can use the outFile object (of class PrintWriter) as we would use System.out: outFile.println(“Hello, how are you?”); outFile.print(“The variable x is ” + x);• We must close the file when we’re finished, to let other users or programs access the file:  outFile.close();© 2004 Pearson Addison-Wesley. All rights reserved 10-21
  22. 22. Reading Text Files• Just as with writing a text file, we must open a file for reading. This stops other users or programs from trying to write to the file at the same time Scanner inScan; String filename= “myfile.txt”; try { inScan= new Scanner( new FileReader(filename)); }• And of course a catch { … } clause© 2004 Pearson Addison-Wesley. All rights reserved 10-22
  23. 23. Reading Text Files• After that, you can use the nextInt(), nextDouble(), nextline() methods on the inScan object• The Scanner class also has a set of methods that allow you to find out if there is any input of a certain type left:  inScan.hasNextLine()  inScan.hasNextInt()  inScan.hasNextDouble()• We also need to close the input file once we are done with it  inScan.close()© 2004 Pearson Addison-Wesley. All rights reserved 10-23

×