OOP-ch04-Exception Handling - Files and IO
OOP-ch04-Exception Handling - Files and IO
Exception Handing –
Files and IO
} of exception.
▪ After the catch finishes, jump to the
statement after all the catch blocks.
Exception Classes
Example
public class Exception1 {
public static void main(String[] args) {
String sNum = "CTB";
String sDate = "10/03/2016";
int num = Integer.parseInt(sNum);
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
Date d = f.parse(sDate);
String s = “Subject - OOP";
System.out.println(s.substring(50));
}
}
Stack Traces
• How do you know what went wrong?
• All exceptions have methods that return information about
the cause of the Exception:
Method Description
getLocalizedMessage() Returns a String containing a description of the
error
getStackTrace() Returns an array of StackTraceElement objects,
each of which contains info about where the
error occurred
Error Exception
IndexOutOfBoundsException NullPointerException
Some runtime (unchecked) exceptions
• The types of exceptions that need not be included in a methods throws list
are called Unchecked Exceptions. They can be foreseen and prevented by a
programmer and, generally speaking, will never occur in a high-quality
program:
• ArithmeticException
• ArrayIndexOutOfBoundsException
• ClassCastException
• IndexOutOfBoundsException
• IllegalStateException
• NullPointerException
• SecurityException
Some checked exceptions
• The types of exceptions that must be included in a methods throws list if
that method can generate one of these exceptions and does not handle it
itself are called Checked Exceptions. Checked exceptions can happen at any
time, cannot be prevented and therefore the language enforces to deal
with them.
• ClassNotFoundException
• CloneNotSupportedException
• IllegalAccessException public class Exception4 {
public static void main(String[]
• InstantiationException args){
• InterruptedException File file = new File(“example.txt");
try{
• NoSuchFieldException file.createNewFile();
• NoSuchMethodException }catch(IOException ex){
System.out.println(ex);
}
} }
throw and throws
• The throw keyword in Java is used to explicitly throw an exception
from a method or any block of code. We can throw either checked or
unchecked exception.
• throws is a keyword in Java which is used in the signature of method
to indicate that this method might throw one of the listed type
exceptions. The caller to these methods has to handle the exception
using a try-catch block.
class ThrowExcep1 {
static void fun(){ class ThrowsExecp2 {
try{ static void fun() throws
throw new IllegalAccessException
NullPointerException("demo"); {
} System.out.println("Inside
catch(NullPointerException e){
System.out.println("Caught fun(). ");
inside fun()."); throw new
throw e; // rethrowing the IllegalAccessException("demo");
exception }
} public static void main(String
} args[]) {
public static void main(String try{
args[]){ fun();
try{
fun(); }
} catch(IllegalAccessException e) {
catch(NullPointerException e) { System.out.println("caught in
System.out.println("Caught in main.");
main."); }
} }
} }
}
Creating Your Own Exception Classes
• Decide whether you want a checked or a runtime exception.
• Checked exceptions should extend java.lang.Exception or one of its
subclasses.
• Runtime exceptions should extend java.lang.RuntimeException or one of its
subclasses
• The argument list of these constructors should include
• A message
class MyException extends Exception {
• A cause MyException() {….. }
• A message and MyException(String s) {
a cause super(s);
….. }}
public class ExceptionDemo {
public static void executeHasException() throws MyException{
throw new MyException();
}
Example (validate)
public class ValidateException extends Exception {
public ValidateException(String message) {
super(message);
}
}
private void validateCode(String id)
throws ValidateException{
if(!id.matches("^[Bb]{1}\\d{2}[A-Za-z]{4}\\d{3}$"))
throw new ValidateException(“Code \""+id+"\“invalid");
}
private void validateDob(String dob)
throws ValidateException{
if(!dob.matches("\\d{2}-\\d{2}-\\d{4}"))
throw new ValidateException(“DOB \""+dob+"\“invalid");
}
Exceptions and Overriding
• When you extend a class and override a method, the Java compiler insists
that all exception classes thrown by the new method must be the same as,
or subclasses of, the exception classes thrown by the original method. In
other words, an overriden method in a sub class must not throw
Exceptions not thrown in the base class. Thus if the overriding method
does not throw exceptions, the program will compile without complain.
class Disk {
void readFile() throws EOFException{}
}
class FloppyDisk extends Disk {
// ERROR!
void readFile() throws IOException {}
}
class DiskFix {
void readFile() throws IOException {}
}
class FloppyDisk extends Disk {
void readFile() throws EOFException {} //OK
}
Exception Propagations
catch(...)
A()
B()
Stack for A()
Stack for B() C()
Java :
• Uses UTF to read/write Unicode
• Helps converting Unicode to external 8-bit encodings and vice versa.
Introduction to the java.io Package
• Java treats all data sources ( file, directory, IO devices,…) as streams
• The java.io package contains Java APIs for accessing to/from a stream.
• A stream can be a binary stream.
• Binary low-level stream: data unit is a physical byte.
• Binary high-level stream: data unit is primitive data type value or a
string.
• Object stream: data unit is an object.
• A stream can be a character stream in which a data unit is an Unicode
character.
Accessing directories and files (1)
The java.io.File Class
Class represents a file or a directory managed by operating system.
Constructor Summary
Java Program
File(File parent, String child)
java.io.File class Creates a new File instance from a parent abstract pathname
and a child pathname string.
File(String pathname)
OS Creates a new File instance by converting the given pathname
string into an abstract pathname.
File(String parent, String child)
Creates a new File instance from a parent pathname string and
Directories/ a child pathname string.
Files
Information File(URI uri)
Creates a new File instance by converting the given file: URI
into an abstract pathname.
Accessing directories and files (2)
The java.io.File Class…
File
2
read() char c;
1 -1?
FileReader
String S;
readLine()
TextFile split
(filename) null?
BufferedReader
ClassA obj;
We must Type field1
know data Type field2
LineNumberReader …………
format in
the file. getLineNumber() int lineCurrentNo;
Writing Data
File class
char c; 2
1
String S; FileWriter class
TextFile
write()
(filename)
concatenate
print()
println()
ClassA obj;
PrintWriter class
Type field1
FileWriter(File file)
Type field2
FileWriter(File file, boolean append)
………… We must design
the data format FileWriter(FileDescriptor fdObj)
READ
Binary Streams
Low-Level Binary Stream Demo
Write
data to
file
A high-level
DataOutputStream
file access
(int, string,…)
includes some
low-level
FileOutputStream access
(byte) ( read an int
value includes
4 times of
File read a byte)
Example (2)
Access Object Files
• 2 Object streams :Object Input stream, Object Output stream
Serialization
• The process of writing an object is called serialization.
• Use java.io.ObjectOutputStream to serialize an object.
• It is only an object’s data that is serialized, not its class definition.
• When an object output stream serializes an object that contains
references to other object, every referenced object is serialized along
with the original object.
• Not all data is written.
• static fields are not
• transient fields are also not serialized
De-serialization
• De-serialization is to convert a serialized representation into a replica
of the original object.
• Use java.io.ObjectInputStream to deserialize an object.
• When an object is serialized, it will probably be deserialized by a
different JVM.
• Any JVM that tries to deserialize an object must have access to that
object’s class definition.
Access Object Files…: How to?
No method is
FileInputStream FileOutputStream
declared
class A implements
ObjectInputStream f; java.io.Serializable ObjectOutputStream
{ Type field1;
Type field2;
………… writeObject()
readObject()
}
null?