Sie sind auf Seite 1von 18

OCP in Java 6.

0 / formerly known as SCJP


Day 9 Notes

Exceptions and Assertions


But because this is a runtime exception, the code will compile without any error from the compiler. Program 1 class TestException { public static void main(String args[]) { int x = 15; int y = 0; System.out.println ("x/y: " + x/y); System.out.println("x + y: " + (x+y)); System.out.println("x-y: " + (x-y)); System.out.println("x*y: " + x*y); } } try { } catch() { } Rule
A catch block is executed only if it catches the exception coming from within the corresponding try block.

try { } catch() {

}
finally { } Program 2 public class ExceptionHandle2 { public static void main(String[] args) { int x = 15; int y = 0; try { System.out.println ("x/y: " + x/y); System.out.println("x*y: " + x*y); } catch (ArrayIndexOutOfBoundsException oe) { System.out.println("An exception occurred: " + oe); } finally { System.out.println("finally block must be executed!"); } System.out.println("x-y: " + (x-y)); } } Rule An exception arises inside the finally block, or a return statement exists in the finally block. The System.exit() method is called before the execution of the finally block.

Using Multiple catch Blocks Program 3 public class MultipleExceptions { public static void main(String[] args) { int[] x = {0, 1, 2, 3, 4}; try { System.out.println ("x[6]: " + x[6]);
2

System.out.println("x[3]: " + x[3]); } catch (ArithmeticException ae) { System.out.println("An arithmetic exception occurred: " + ae); } catch (ArrayIndexOutOfBoundsException oe) { System.out.println("Array index out of bound! "); } catch (IndexOutOfBoundsException ie) { System.out.println("Some kind of index out of bound! "); } finally { System.out.println("finally block must be executed!"); } System.out.println("x[0]: " + x[0]); } } Rule
The catch block with a more specific exception must appear before the catch block with a less specific exception. If more than one matching catch blocks exist, the first one encountered would be executed, and it would be the most specific one.

Control Flow in Exception Condition

Throwing Exceptions
Program 4

public class ThrowExample { public static void main(String[] args) { double x = 15.0; double y = 0.0; try { ThrowExample te = new ThrowExample(); double z = te.doubleDivide(x, y); System.out.println ("x/y: " + x/y); } catch (ArithmeticException ae) { System.out.println("An exception occurred: " + ae); } System.out.println("x-y: " + (x-y)); } double doubleDivide(double x, double y) { if(y==0.0)

{ throw new ArithmeticException("Integer or not,please do not divide by zero!"); } else { return x/y; } } } Type of Exceptions Two types 1. Unchecked or Runtime Exception -- checked by the JVM 2. Checked Exceptions -- checked by the compiler
Exception Tree in Java

Some Standard Exceptions

Checked Exception:
1. Duck It / throws 2. or Catch It / try catch it

void callingMethod() { calledMethod(); } void calledMethod() throws IOException { throw new IOException(); }
void callingMethod() throws IOException {

Declaring Exceptions when Overriding Program 5 import java.io.*; public class OverrideException { public void someMethod() throws IOException { } } class SubClassLegalOne extends OverrideException { public void someMethod() throws IOException { } } class SubClassLegalTwo extends OverrideException { public void someMethod() { } } class SubClassLegalThree extends OverrideException

{ public void someMethod() throws EOFException, FileNotFoundException { } } class SubClassIllegalOne extends OverrideException { public void someMethod() throws ClassNotFoundException { } } class SubClassIllegalTwo extends OverrideException { public void someMethod() throws Exception { } } class SubClassIllegalThree extends OverrideException { public void someMethod() throws IOException, ClassNotFoundException { } } Rule If the overridden method does not throw any exception, the overriding method cannot throw any checked exception, but it can still throw a runtime exception. If the overridden method throws an exception, its legal for the overriding method to throw no exception.

Assertions For debugging purpose

Sometimes in programming, there are some assumptions that must be true; for example, if you are going to calculate the square root of a number, the number must be positive. To facilitate the test of such assumptions, Java offers the assertion facility, which refers to the verification of a condition that is expected to be true during the execution of a program. It is implemented using the keyword assert, introduced to the Java language in Java 2, version 1.4.

assert <condition>; or assert <condition>:<expression>; Program 6 public class AssertionExample { public static void main(String[] args) { int x = 15; DataAccess da = new DataAccess(); assert da.dataIsAccesible():"Data is not acceptable"; System.out.println("Value of x: " + x); } } class DataAccess { public boolean dataIsAccesible() { return false; } }
javac -source 1.4 AssertionExample.java java -ea AssertionExample Rule The compiler flag source 1.4 is not necessary in version 5.0; it was required in version 1.4. However, assertions are turned off by default during execution of the program.

Input and Output in Java

File Path consider the following path name on a Unix/Linux machine: /java/scjp/temp The first forward slash represents the root directory. This path name in Windows machines may be written as C:\java\scjp\temp

File Class
The java.io package offers the File class to enable you to work with the file system on your machine.

10

Program 1 import java.io.*; class TestFileConstructors { public static void main (String[] args) { try { File f1 = new File("java/scjp"); File f2 = new File("java/scjp", "temp/myProg.java"); File f3 = new File(f1, "temp/myProg.java"); System.out.println("path for f1: " + f1.getCanonicalPath()); System.out.println("path for f2: " + f2.getCanonicalPath()); System.out.println("path for f3: " + f3.getCanonicalPath()); } catch (IOException ioe) { ioe.printStackTrace(); } } }

Navigating the File System


boolean canRead(): Returns true if the file (or directory) represented by the File instance can be read by the program. boolean canWrite(): Returns true if the file (or directory) represented by the File instance can be modified by the program. boolean createNewFile(): Creates a new file by using the abstract name associated with the File instance, if and only if the file with this path name does not exist already. boolean delete(): Deletes the file or directory represented by this File instancethat is, denoted by the abstract path name associated with this File instance. boolean exists(): Returns true if the file (or directory) denoted by the path name associated with this File instance exists. String getAbsolutePath(): Returns the absolute (as opposed to relative) path, also called full path, of the file (or directory) represented by this File instance.

11

String getCanonicalPath(): Same as getAbsolutePath(), but the separators in the path name are system-dependent separators (such as / or \). String getName(): Returns the name of the file (or directory) represented by this File instance. String getParent(): Returns the name of the file (or directory) that contains the file (directory) represented by this File instance. boolean isAbsolute(): Returns true if the path name associated with this File instance is an absolute path name (as opposed to a relative path name). boolean isDirectory(): Returns true if this File instance represents a directory (as opposed to a normal file). boolean isFile(): Returns true if this File instance represents a normal file (as opposed to a directory). String[] list(): Returns an array that contains the names of files and directories contained in the directory represented by this File instance. Obviously, this method should only be invoked on a File instance that represents a directory.

Program 2
import java.io.*; class FileNavigator { public static void main (String[] args) { String treeRoot = "."; //default root if (args.length >=1)treeRoot=args[0]; File rootDir = new File(treeRoot); System.out.println("Root of navigation:" + rootDir.getAbsolutePath()); // check if the root exists as a directory. if(!(rootDir.isDirectory())) { System.out.println("The root of the naviagtion subtree does not exist as a directory!"); System.exit(0); } FileNavigator fn = new FileNavigator(); fn.navigate(rootDir); } public void navigate(File dir) { System.out.println(" "); System.out.println("Directory " + dir + ":"); String[] dirContent = dir.list(); for (int i=0; i<dirContent.length; i++) { System.out.print(" " + dirContent[i]); File child = new File(dir, dirContent[i]); if(child.isDirectory()) navigate(child);

12

} } }

Streams
the sequence of data items such as bytes

Low-Level Streams A low-level input stream reads data and returns it in bytes, and a low-level output stream accepts data as bytes and writes the output in bytes. Two examples of low-level streams are represented by the classes FileInputStream and FileOutputStream, which are subclasses of InputStream and OutputStream, respectively.
The FileInputStream Class The FileInputStream class is designed for reading image files as it reads a stream of raw bytes. FileOutputStream Class The FileOutputStream class is meant for writing streams of raw bytes into files, such as image files.

Program 3
import java.io.*; public class FileByteCopier { public static void main(String[] args) throws IOException { File inputFile = new File("scjp.txt"); File outputFile = new File("scjpcopy.txt"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1)out.write(c); in.close(); out.close(); } }

13

The High-Level Streams


When the unit of information you are interested in is a high-level data type such as a float, an int, or a String, and you dont want to deal with bytes directly, you can work with high-level streams. The DataInputStream Class Java offers the DataInputStream class to enable an application to read primitive data types from an underlying input stream in a machineindependent way. However, as Figure 8-2 shows, it does not read directly from an input device such as a file, but rather is attached to a low-level stream that reads bytes from the input device and processes the bytes into values of desired high-level data types.

The DataOutputStream Class Java offers the DataOutputStream class to enable an application to write primitive data types to an underlying output stream in a machine-independent way.

Program 4
import java.io.*; public class ReadWriteDataTest { public static void main(String[] args) throws IOException {

14

String dataFile = "orders.txt"; DataOutputStream out = new DataOutputStream(new FileOutputStream(dataFile)); double[] priceList = { 19.99, 29.99, 39.99}; int[] copies = { 100000, 50000,70000}; String[] titleList = { "SCJP Study Guide", "SCBCD Study Guide" , "SCSA Study Guide"}; // Write out into the file. for (int i = 0; i < priceList.length; i++) { out.writeDouble(priceList[i]); out.writeChar('\t'); out.writeInt(copies[i]); out.writeChar('\t'); out.writeChars(titleList[i]); out.writeChar('\n'); } out.close(); // read back in again DataInputStream in = new DataInputStream(new FileInputStream(dataFile)); double price; int copy; StringBuffer title; double grandTotal = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); //throws away the tab copy = in.readInt(); in.readChar(); //throw away the tab char ch; title = new StringBuffer(25); char lineSep = System.getProperty("line.separator").charAt(1); while ((ch = in.readChar()) != lineSep)title.append(ch); System.out.println("Your order: " + copy + " copies of " + title + " at $" + price); grandTotal = grandTotal + copy * price; } } catch (EOFException e) { System.out.println("End of File!"); } System.out.println("Grand Total: $" + grandTotal); in.close(); } } Readers and Writers To read and write data FileInputStream/FileOutputStream in binary (low-level format, you streams) have and

15

DataInputStream/DataOutputStream (high-level streams). To read data in text format, Java offers so-called reader and writer streams.

Low-Level Readers and Writers


The low-level reader streams read data and return it in characters, and lowlevel output streams accept data as characters and write the output in characters. Two examples of low-level reader and writer streams are FileReader and FileWriter.

High-Level Readers and Writers


As you know, you can use DataInputStream and DataOutputStream to read and write the primitive types in binary format. Similarly, you can read and write characters in character streams in big chunks (buffers) and in text format by using the BufferedReader and BufferedWriter classes, respectively.

Program 5
import java.io.*; public class FileBufferCopier { public static void main(String[] args) throws IOException { File inputFile = new File("scjp.txt"); File outputFile = new File("scjpcopy.txt"); BufferedReader in = new BufferedReader(new FileReader(inputFile)); BufferedWriter out = new BufferedWriter(new FileWriter(outputFile)); String line; while ((line = in.readLine()) != null){ out.write(line); out.newLine(); } in.close(); out.close(); } }

Object Streams and Serialization


The process of writing an object to somewhere is called object serialization, and the process of reading a serialized object back into the program is called deserialization. class MySerialClass implements Serializable {

16

// body of the class }

Writing with ObjectOutputStream


To write an object to a file, you use the ObjectOutputStream to write it to a low-level stream, which in turn will write it to the file. For example, consider the following code fragment: FileOutputStream out = new FileOutputStream("objectStore.ser"); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject("serialOut"); os.writeObject(new MySerialClass()); os.writeObject("End of storage!"); os.flush();

Reading with ObjectInputStream


Once youve written objects and primitive data types to a stream, youll likely want to read them again and reconstruct the objects. This is also straightforward. Here is a code fragment that reads in the String and the Date objects that were written to the file named objectStore.ser in the previous example: FileInputStream in = new FileInputStream("objectStore.ser"); ObjectInputStream is = new ObjectInputStream(in); String note = (String)is.readObject(); MySerialClass serialIn1 = (MyClassSerial)is.readObject(); MySerialClass serialIn2 = (MyClassSerial)is.readObject(); Program 6 import java.io.*; class CodeWalkSeven { public static void main(String [] args) { Car c = new Car("Nissan", 1500, "blue"); System.out.println("before: " + c.make + " " + c.weight); try { FileOutputStream fs = new FileOutputStream("Car.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(c); os.close(); }catch (Exception e) { e.printStackTrace(); } try { FileInputStream fis = new FileInputStream("Car.ser"); ObjectInputStream ois = new ObjectInputStream(fis); c = (Car) ois.readObject(); ois.close();

17

}catch (Exception e) { e.printStackTrace(); } System.out.println("after: " + c.make + " " + c.weight); } } class NonLiving {} class Vehicle extends NonLiving { String make = "Lexus"; String color = "Brown"; } class Car extends Vehicle implements Serializable { protected int weight = 1000; Car(String n, int w, String c) { color = c; make = n; weight = w; } }

18

Das könnte Ihnen auch gefallen