Download presentation
Presentation is loading. Please wait.
Published byLeo Mosley Modified over 8 years ago
1
Chapter 12 Exceptions and Advanced File I/O
2
2 Contents I. Handling Exceptions II. Throwing Exceptions III. Advanced Topics 1. Binary Files 2. Random Access Files 3. Object Serialization
3
3 I. Handling Exceptions This program causes an error and crashes. public class BadArray { public static void main(String[] args) { //Create an array with 3 elements int[] numbers = {1, 2, 3}; //Attempt to read beyond the bounds of the array for(int i = 0; i <= 3; i++) System.out.println(numbers[i]); } }
4
4 I. Handling Exceptions An exception is an object that is generated in memory as the result of an error about it. When an exception is generated, it is said to have been “thrown”. Unless an exception is detected by the application and dealt with, it causes the application to halt. To detect that an exception has been thrown and prevent it from halting your application, Java allows us to create exception handler.
5
5 I. Handling Exceptions An exception is a section of code that gracefully responds to exceptions when they are thrown. The process of intercepting and responding to exceptions is called exception handling. If our program does not handle an exception when it is thrown, the default exception handler deals with it. The default exception handler prints an error message and crashes the program.
6
6 Exception Classes
7
7 Error : Exceptions that are thrown when a critical error occurs, such as an internal error in the JVM or running out of memory. Exception : All of exceptions that we will handle. RuntimeException : Exceptions that result from programming errors, such as an out-of- bounds array subscript.
8
8 Exception Classes IOException : Related to input and output operations. EOFException : Thrown when the program reads beyond the end of file. FileNotFoundException : Thrown when the program tries to open a file that does not exist.
9
9 Handling an Exception To handle an exception, we use try statement. try { (try block statements …) } catch(ExceptionType parameterName) { (catch block statements …) }
10
10 Handling an Exception try block: A try block is one or more statements that are executed and potentially throw an exception. The code in the try block is protected because the application will not halt if the try block throws an exception. catch clause: If the code in the try block throws an exception of the ExceptionType class, then the parameterName will reference the exception object. In addition, the code in catch block is executed.
11
11 Handling an Exception try { File file = new File(“MyFile.txt”); Scanner inputFile = new Scanner(file); } catch (FileNotFoundException e) { System.out.println(“File is not found.”); }
12
12
13
13 Retrieving the Default Error Message Each exception object has a method named getMessage that can be used to retrieve the default error message for the exception.
14
14
15
15
16
16 Polymorphic References to Exceptions Recall that a reference variable of a superclass type can reference subclass objects. try { number = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Conversion error: " + e.getMessage()); } Although the Integer.parseInt method throws a NumberFormatException object, the code still works because the NumberFormatException class inherits from the Exception class.
17
17 Handling Multiple Exceptions The code in try block will be capable throwing more than one type of exception. We need to write a catch clause for each type of exception that could be potentially be thrown.
18
18
19
19
20
20 Using Exception Handlers to Recover from Errors
21
21
22
22
23
23 Handle Each Exception Only Once in a try Statement Not including polymorphic references, a try statement may have only one catch clause for each specific type of exception. try { number = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println(“Bad number format.”); } //Error: NumberFormatException has already been caught! catch (NumberFormatException e) { System.out.println(str + “ is not a number”); }
24
24 Handle Each Exception Only Once in a try Statement Sometimes we can cause this error by using polymorphic references. try { number = Integer.parseInt(str); } catch(IllegalArgumentException e) { System.out.println(“Bad number format.”); } //Error: This will also cause an error. catch(NumberFormatException e) { System.out.println(str + “ is not a number”); }
25
25 Handle Each Exception Only Once in a try Statement try { number = Integer.parseInt(str); } catch(NumberFormatExceptionx e) { System.out.println(“Bad number format.”); } catch(IllegalargumentException e) { System.out.println(str + “ is not a number”); } We should handle the more specialized exception classes before the general exception classes.
26
26 The finally Clause The try statement may have an optional finally clause, which must appear after all of the catch clauses. try { (try block statememts...) } catch(ExceptionType e) { (catch block statements...) } finally { (finally block statements...) }
27
27 The finally Clause The finally block is one or more statements that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown. The statements in the finally block execute whether an exception occurs or not.
28
28
29
29 The Stack Trace Quite often, a method will call another method, which will call yet another method. For example, method A calls method B, which calls method C. The call stack is an internal list of all the methods that are currently executing. A stack trace is a list of all methods in the call stack.
30
30
31
31 The Stack Trace In the previous program, the exception is not handled by the program, but is dealt with by the default exception handler. When the exception occurs, the error message shows stack trace listing the methods that were called in order to produce the exception. All exception objects have a printStackTrace method, inherited from the Throwable class, which can be used to print a stack trace.
32
32 When an Exception Is Not Caught When an exception is thrown, it cannot be ignored. It must be handled by the program, or by the default exception handler. If there is no code inside the method to handle the exception, then control of the program is passed to the previous method in the call stack. If that method does not handle the exception, then control is passed again, up the call stack, to the previous method. This continues until control reaches the main method.
33
33 When an Exception Is Not Caught If the main method does not handle the exception, then the program is halted and the default exception handler handles the exception.
34
34 Checked and Unchecked Exceptions In Java, there are two categories of exceptions: unchecked and checked. Unchecked exceptions are those that inherited from: the Error class the RuntimeException class All of the remaining exceptions are checked exceptions.
35
35 Checked and Unchecked Exceptions Unchecked exceptions: It is best not to handle these exceptions, because they can be avoided with properly written code. We should not handle unchecked exceptions. Checked exceptions: We should handle these exceptions. If the code in the method can throw a checked exception, that method must meet one of the following requirements: It must handle the exception, or It must have a throws clause listed in the method header.
36
36 Checked and Unchecked Exceptions The throws clause informs the compiler of the exceptions that could get thrown from a method. //This method will not compile! public void displayFile(String name) { File file = new File(name); Scanner inputFile = new Scanner(file); … } The code is capable of throwing a FileNotFoundException, which is a checked exception. Because the method does not handle this exception, it must have a throws clause in its header.
37
37 Checked and Unchecked Exceptions public void displayFile(String name) throws FileNotFoundException { File file = new File(name); Scanner inputFile = new Scanner(file); … } The throws clause tells the compiler that this method can throw a FileNotFoundException. If there is more than one type of exceptions, we separate them with commas.
38
38 II. Throwing Exceptions We can write code that throws one of the standard Java exceptions, or an instance of a custom exception class that we have designed. We use the throw statement to throw an exception manually: throw new ExceptionType(MessageString); Causes an exception object to be created and thrown. MessageString is a custom error message that can be retrieved from the exception object's getMessage method.
39
39 II. Throwing Exceptions
40
40
41
41 II. Throwing Exceptions In the above program The constructor is capable of throwing an exception of IllegalArgumentException. It is an unchecked exception. We don't need to put a throws clause in the constructor's header. If we had chose a checked exception class, we would have to put a throws clause in the constructor's header.
42
42 Creating Your Own Exception Classes We can create our own exception classes by extending the Exception class or its subclasses. For example, there are a number of errors that could cause a BankAccount object to perform its duties incorrectly. Negative starting balance is passed to the constructor. Creating an exception class for a negative starting balance....
43
43
44
44 /** This constructor sets the starting balance to the value passed as an argument. @param startBalance The starting balance. @exception NegativeStartingBalance When startBalance is negative. */ public BankAccount(double startBalance) throws NegativeStartingBalance { if (startBalance < 0) throw new NegativeStartingBalance(startBalance); balance = startBalance; }
45
45 Using the @exception Tag in Documentation Comments We can document the exceptions thrown by a method by using an @exception tag. @exception ExceptionName Description
46
46 Checkpoint 12.15 What does the throw statement do? 12.16 What is the purpose of the argument that is passed to an exception object's constructor? What happens if you do not pass an argument to the constructor? 12.17 What is the difference between the throw statement and the throws clause? 12.18 If a method has a throw statement, does it always have to have a throw clause in its header? Why or why not? 12.19 If you are writing a custom exception class, how can you make sure it is checked? How can you make sure it is unchecked?
47
47 III. Advanced Topics Binary Files A file that contains raw binary data is known as a binary file. The contents of a binary file is not formated as text, and not meant to be opened in a text editor. Random Access Files A random access file is a file that allows a program to read data from any location within a file, or write data to any location within the file. Object Serialization Object serialization is the process of converting an object to a series of bytes and saving them to a file. Deserialization is the process of reconstructing a serialized object.
48
48 III.1 Binary Files Text Files When a number is stored in a text file with the print or println method, it is converted to text. PrintWriter outputFile = new PrintWriter(“Number.txt”); int x = 12345; outputFile.print(x); The number 12345 is stored as the characters '1', '2', '3', '4', and '5'.
49
49 III.1 Binary Files Binary Files When a number such as 12345 is stored in the computer's memory, it is formated as a binary number. It is called the raw binary format. Data can be stored in a file in its raw binary format. A file that contains binary data is often called a binary file.
50
50 III.1 Binary Files Storing data in its binary format is more efficient than storing it as text because There are fewer conversions to take place There are some types of data that should only be stored in their raw binary format. Images However, when data is stored in a binary file, we cannot open the file in a text editor.
51
51 Writing Data to a Binary File To write data to a binary file, we must create objects from the following classes: FileOutputStream Allows you to open a file for writing binary data and establish a connection with it. It provides only basic functionality for writing bytes to the files, however. DataOutputStream Allows you to write data of any primitive type or String objects to a binary file. This class cannot directly access a file. It is used in conjunction with a FileOutputStream object.
52
52 Writing Data to a Binary File FileOutputStream fstream = new FileOutputStream(“MyInfo.dat”); DataOutputStream outputFile = new DataOutputStream(fstream); If the file already exists, it will be erased and an empty file by the same name will be created. The FileOutputStream constructor throws an IOException if an error occurs when it attempts to open the file. If there is no reason to reference fstream, these statements can be combined into one. DataOutputStream outputFile = new DataOutputStream(new FileOutputStream(“MyInfo.dat”));
53
53 Writing Data to a Binary File Some of the DataOutputStream methods void close() void writeBoolean(boolean b) void writeByte(byte b) void writeChar(int c) void writeDouble(double d) void writeFloat(float f) void writeLong(long l) void writeShort(short s) void writeUTF(String str)
54
54
55
55 Reading Data from a Binary File To open a binary file for input, you use the following classes: FileInputStream Allows you to read data for reading binary data and establish a connection with it. It provides only the basic functionality for reading bytes from the file, however. DataInputStream Allows you to read data of any primitive type, or String objects, from a binary file. This class cannot directly access a file. It is used in conjunction with a FileIntputStream object.
56
56 Reading Data from a Binary File To open a binary file for input: FileIntputStream fstream = new FileIntputStream(“MyInfo.dat”); DataInputStream inputFile = new DataInputStream(fstream); Or DataInputStream inputFile = new DataInputStream(new FileIntputStream(“MyInfo.dat”));
57
57 Reading Data from a Binary File Some of the DataInputStream methods void close() boolean readBoolean() byte readByte() char readChar() double readDouble() float readFloat() long readLong() short readShort() String readUTF()
58
58 Reading Data from a Binary File Notice that the code for reading data must catch the EOFException in order to determine when the file's end has been reached.
59
59
60
60 Reading Data from a Binary File Writing and Reading Strings To write a string to a binary file you should use the DataOutputStream class's writeUTF method. This method writes a String in a format known as UTF-8 encoding. Just before writing the string, this method writes a two- byte integer indicating the number of bytes that the string occupies. Then it writes the string's characters in Unicode. When the method readUTF reads from a file, it expects the first two bytes to contain the number of bytes that the string occupies. Then it reads that many bytes and returns them as a String.
61
61 Appending Data to an Existing Binary File To append new data to the end of the binary file: FileOutputStream fstream = new FileOutputStream(“MyInfo.dat”, true); DataOutputStream outputFile = new DataOutputStream(fstream);
62
62 III.2 Random Access Files Sequential file access: When a file is opened for input, its read position is at the beginning of the file. As the reading continues, the file's read position advances sequentially through the file's contents. The problem: If the program needs data stored at the hundredth byte of a file, it will have to read the first 99 bytes to reach it. To listen to a song at the end of the tape, you have to listen to all the songs that are before it, or fast forward over them. There is no way to jump immediately to that particular song.
63
63 III.2 Random Access Files Java allows a program to perform random file access. A program may immediately jump to any location in the file without first reading the preceding bytes. The different between sequential and random file access is like the difference between a cassette tape and a compact disc.
64
64 III.2 Random Access Files To create and work with random access files in Java, you use the RandomAccessFile class. The constructor RandomAccessFile(String filename, String mode) mode : is a string indicating the mode in which you wish to use the file. “r” : Open the file for reading, if the file does not exists, a FileNotFoundException will be thrown. If you try to write to it, an IOException will be thrown “rw” : Open the file for reading and writing. If the file does not exist, it will be created. If the file exists, the file's contents will be preserved.
65
65 III.2 Random Access Files Open a file for random reading RandomAccessFile randomFile = new RandomAccessFile(“MyData.dat”, “r”); Open a file for random reading and writing RandomAccessFile randomFile = new RandomAccessFile(“MyData.dat”, “rw”);
66
66 III.2 Random Access Files The RandomAccessFile class: Has the same methods as the DataOutputStream class for writing data. Has the same methods as DataInputStream class for reading data. In fact, we can use the RandomAccessFile class to process a binary file sequentially.
67
67
68
68 The File Pointer The RandomAccessFile class treats a file as a stream of bytes. The bytes are numbered (similar to an array's subscripts), with the first byte being byte 0. The last byte's number is one less than the number of bytes in the files. The file pointer holds the byte number of a location in the file. Reading and writing occur at the location that the file pointer points to. When a file is first opened, the file pointer is set to 0. This causes it to point to the first byte in the file. Reading causes the file pointer to advance to the byte just beyond the item that was read.
69
69 The File Pointer If the file pointer refers to a byte number that is beyond the end of the file: When a read operation is performed, an EOFException is thrown. When a write operation is peformed, the data will be written to the end of the file. The RandomAccessFile class allows you to move the file pointer. void seek(long position) : To move the file pointer to position.
70
70 The File Pointer RandomAccessFile file = new RandomAccessFile("Letters.dat", "rw"); file.seek(99); // Moves to the 100 th byte byte b = file.readByte(); //Read the 100 th byte, and the file pointer is 100. file.seek(49); //Moves to the 50 th byte int i = file.readInt(); //Read 4 bytes, and the file pointer is 53.
71
71 The File Pointer The RandomAccessFile class see a file only as a stream of bytes. The class is unaware of the data types of the data stored in the file. It cannot determine where one item of data ends and another begins. When we read data from a random access file, it is our responsibility to know how the data is structured.
72
72 The File Pointer Suppose the file Letters.dat contains a sequence of letters. The first letter is character 0, the second letter is character 1, and so forth. We want to read the character 5 (the sixth letter in the file). What will this display? RandomAccessFile file = new RandomAccessFile("Letters.dat", "r"); file.seek(5); char ch = file.readChar(); System.out.println(“The sixth letter is “ + ch); 1. The sixth character begins at byte 10, not byte 5. 2. We will read garbage because byte 5 is not at the beginning of a character.
73
73 The File Pointer To determine the position of a character in the file, we must take each character's size into account. final int CHAR_SIZE = 2; //each char uses 2 bytes file.seek(CHAR_SIZE * 5); char ch = file.readChar(); System.out.println(“The sixth character is “ + ch);
74
74 III.3 Object Serialization When an object is serialized, it is converted into a series of bytes that contain the object's data. The resulting series of bytes can be saved to a file for later retrieval. In order for an object to be serialized, its class must implement the Serializable interface. The Serializable interface has no methods or fields, it is used only to let the Java compiler know that objects of the class might be serialized. If a class contains objects of other classes as fields, those classes must also implement this interface in order to be serialized.
75
75 III.3 Object Serialization To write a serialized object to a file, you use an ObjectOutputStream object. This class is designed to perform the serialization process. To write the bytes to a file, you must also use an output stream object, such as FileOutputStream. FileOutputStream fs = new FileOutputStream(“Objects.dat”); ObjectOutputStream objectOutputFile = new ObjectOutputStream(fs);
76
76 III.3 Object Serialization To serialize an object and write it to a file, use the ObjectOutputStream class's writeObject method: Suppose that public class BankAccount2 implements Serializable.... BankAccount 2 account = new BankAccount2(5000); objectOutputFile.writeObject(accout);
77
77 III.3 Object Serialization Deserialization The process of reading a serialized object's bytes and constructing an object from them. To deserialize an object you use an ObjectInputStream object, along with a FileInputStream object. FileInputStream fs = new FileInputStream(“Objects.dat”); ObjectInputStream objectInputFile = new ObjectInputStream(fs);
78
78 III.3 Object Serialization To read a serialized object from a file, use the ObjectInputStream class's readObject method. BankAccount2 account; accout = (BackAccount2) objectInputFile.readObject();
79
79 Serializing Aggregate Object If a class implements the Serializable interface, then all of the fields in that class must be serializable. This isn't a problem for primitive variables. If the class has a reference variable as a field, then the object referenced by that variable should also be serializable. This means that the object's class should also implement the Serializable interface. If it doesn't, then the transient keyword should be used in the ref variable declaration. The compiler will skip the object during the serialization process. private transient SomeClass refVar;
80
80 Checkpoint 12.20 What is the difference between a text file and a binary file? 12.21 What classes do you use to write output to a binary file? What classes do you use to read from a binary file? 12.22 What is the difference between sequential and random access? 12.23 What class do you use to work with random access file? 12.24 What are the 2 modes that a random access file may be opened in? Explain. 12.25 What must you do to a class in order to serialize objects of that class?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.