Upload
islamshafiq
View
214
Download
0
Embed Size (px)
Citation preview
8/3/2019 Day 9 Notes
1/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 willcompile 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(){}
RuleA catch block is executed only if it catches the exception coming from withinthe corresponding try block.
try{}catch()
{
1
8/3/2019 Day 9 Notes
2/18
}finally{}
Program 2public 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 inthe 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
8/3/2019 Day 9 Notes
3/18
System.out.println("x[3]: " + x[3]);}catch (ArithmeticException ae){
System.out.println("An arithmeticexception occurred: " + ae);
}catch (ArrayIndexOutOfBoundsException
oe){
System.out.println("Array index out ofbound! ");
}
catch (IndexOutOfBoundsException ie){System.out.println("Some kind of
index out of bound! ");}finally{
System.out.println("finally block mustbe executed!");
}System.out.println("x[0]: " + x[0]);}
}
Rule
The catch block with a more specific exception must appear before the catchblock with a less specific exception. If more than one matching catch blocksexist, the first one encountered would be executed, and it would be the most
specific one.
Control Flow in Exception Condition
3
8/3/2019 Day 9 Notes
4/18
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)
4
8/3/2019 Day 9 Notes
5/18
{
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
5
8/3/2019 Day 9 Notes
6/18
Some Standard Exceptions
6
8/3/2019 Day 9 Notes
7/18
Checked Exception:
1. Duck It / throws2. 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
7
8/3/2019 Day 9 Notes
8/18
{public void someMethod() throws
EOFException, FileNotFoundException{
}}class SubClassIllegalOne extends OverrideException{
public void someMethod() throwsClassNotFoundException
{}
}
class SubClassIllegalTwo extends OverrideException{public void someMethod() throws Exception{}
}class SubClassIllegalThree extendsOverrideException{
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 legalfor the overriding method to throw no exception.
Assertions
For debugging purpose
8
8/3/2019 Day 9 Notes
9/18
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, thenumber must be positive. To facilitate the test of such assumptions, Javaoffers the assertion facility, which refers to the verification of a condition that isexpected 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 ;
or
assert :;
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 requiredin version 1.4. However, assertions are turned off by default during executionof the program.
9
8/3/2019 Day 9 Notes
10/18
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 inWindows machines may be written as
C:\java\scjp\temp
File ClassThe java.io package offers the File class to enable you to work with the filesystem on your machine.
10
8/3/2019 Day 9 Notes
11/18
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 theFile instance can be read by the program. boolean canWrite(): Returns true if the file (or directory) represented by theFile instance can be modified by the program. boolean createNewFile(): Creates a new file by using the abstract nameassociated with the File instance, if and only if the file with this path namedoes not exist already. boolean delete(): Deletes the file or directory represented by this Fileinstancethat is, denoted by the abstract path name associated with this Fileinstance. boolean exists(): Returns true if the file (or directory) denoted by the pathname 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
8/3/2019 Day 9 Notes
12/18
String getCanonicalPath(): Same as getAbsolutePath(), but the separators inthe path name are system-dependent separators (such as / or \). String getName(): Returns the name of the file (or directory) represented bythis 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 Fileinstance 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 (asopposed to a directory). String[] list(): Returns an array that contains the names of files anddirectories contained in the directory represented by this File instance.Obviously, this method should only be invoked on a File instance thatrepresents a directory.
Program 2import java.io.*;class FileNavigator{
public static void main (String[] args){
String treeRoot = "."; //default rootif (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 subtreedoes 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
8/3/2019 Day 9 Notes
13/18
}}
}
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 alow-level output stream accepts data as bytes and writes theoutput in bytes. Two examples of low-level streams arerepresented 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 astream of raw bytes.
FileOutputStream Class
The FileOutputStream class is meant for writing streams of raw bytes intofiles, such as image files.
Program 3import 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
8/3/2019 Day 9 Notes
14/18
The High-Level Streams
When the unit of information you are interested in is a high-level data typesuch 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 readprimitive data types from an underlying input stream in a machine-independent way. However, as Figure 8-2 shows, it does not read directlyfrom an input device such as a file, but rather is attached to a low-level streamthat reads bytes from the input device and processes the bytes into values ofdesired high-level data types.
The DataOutputStream Class
Java offers the DataOutputStream class to enable an application to writeprimitive data types to an underlying output stream in a machine-independentway.
Program 4import java.io.*;public class ReadWriteDataTest{public static void main(String[] args) throws IOException{
14
8/3/2019 Day 9 Notes
15/18
String dataFile = "orders.txt";DataOutputStream out = new DataOutputStream(newFileOutputStream(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 againDataInputStream in = new DataInputStream(newFileInputStream(dataFile));double price;int copy;StringBuffer title;double grandTotal = 0.0;try {while (true) {price = in.readDouble();in.readChar(); //throws away the tabcopy = in.readInt();in.readChar(); //throw away the tabchar 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 WritersTo read and write data in binary format, you have
FileInputStream/FileOutputStream (low-level streams) and
15
8/3/2019 Day 9 Notes
16/18
DataInputStream/DataOutputStream (high-level streams). To read data in textformat, 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 low-level output streams accept data as characters and write the output incharacters. Two examples of low-level reader and writer streams areFileReader and FileWriter.
High-Level Readers and Writers
As you know, you can use DataInputStream and DataOutputStream to readand write the primitive types in binary format. Similarly, you can read and writecharacters in character streams in big chunks (buffers) and in text format byusing 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 calleddeserialization.
class MySerialClass implements Serializable {
16
8/3/2019 Day 9 Notes
17/18
// body of the class}
Writing with ObjectOutputStream
To write an object to a file, you use the ObjectOutputStream to write it to alow-level stream, which in turn will write it to the file. For example, considerthe 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 likelywant to read them again and reconstruct the objects. This is alsostraightforward. Here is a code fragment that reads in the String and the Dateobjects that were written to the file named objectStore.ser in the previousexample:
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
8/3/2019 Day 9 Notes
18/18
}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