Beruflich Dokumente
Kultur Dokumente
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.
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
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.
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.
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(); } } }
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 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.
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(); } }
16
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