Lecture Slide - Week 7
Lecture Slide - Week 7
PROGRAMMING
USING JAVA
Introduction
Default Exceptional handler
try
OUTLINE catch
finally
throw
throws
WHAT IS EXCEPTION??
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
Exceptional handling does not mean repairing an exception.
Here we have to provide alternative way to continue the rest of the program
normally is the concept of exceptional handling.
Output :
Bennett University
DEFAULT EXCEPTIONAL HANDLING IN JAVA
Output
DEFAULT EXCEPTIONAL HANDLING IN JAVA (PROCESS)
If an exception raised, the method in which it’s raised is
responsible for the creation of Exceptions object by • If the main() method also doesn’t contain
including the following information: exception handling code the JVM terminates
• Name of the Exception that main() method and removes the
• Description of the Exception corresponding entry from the stack.
• Stack Trace • Just before terminating the program abnormally
• After creating Exception object the method JVM handovers the responsibility of exception
handover it to the JVM. handling to the Default Exception Handler which
• JVM checks for Exception Handling code in that is the component of JVM.
method. • Default Exception Handler just print exception
If the method doesn’t contain any Exception handling code information to the console in the following
then JVM terminates the method abnormally and removes format:
the corresponding entry from the stack.
• JVM identify the caller method and checks for Name of Exception: Description
Exception Handling code in that method. If the caller
doesn’t contain any exception handling code then JVM Stack Trace (Location of the Exception)
terminates that method abnormally and removes the
corresponding entry from the stack.
• This process will be continue until main() method.
EXAMPLE:
EXAMPLE:
PREDICT THE OUTPUT??
PREDICT THE OUTPUT??
NOTE:
The compiler checks a checked exception. The compiler does not check these types of exceptions.
These types of exceptions can be handled at the time of These types of exceptions cannot be a catch or handle at the time
compilation. of compilation, because they get generated by the mistakes in the
program.
They are the sub-class of the exception class. They are runtime exceptions and hence are not a part of the
Exception class.
Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch and handle.
There are given some scenarios where unchecked exceptions can occur. They
are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
COMMON SCENARIOS WHERE EXCEPTIONS MAY OCCUR
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
COMMON SCENARIOS WHERE EXCEPTIONS MAY OCCUR
if you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
JAVA EXCEPTION HANDLING KEYWORDS
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
try{
//code that may throw exception
}finally{}
CATCH BLOCK
output
PROBLEM USING TRY-CATCH
PROBLEM USING TRY-CATCH
Risky code
The code which may rise an exception is called risky code and
we have to define that code inside try block and corresponding
handling code we have to define inside catch block.
output
INTERNAL WORKING OF JAVA TRY-CATCH BLOCK
EXPLANATION
• The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
Termination:normal
CONTROL FLOW INTRY CATCH
Case 2: if there is an exception in statement 2 of try
CONTROL FLOW IN TRY CATCH
Case 2: if there is an exception in statement 2 of try
Order of
execution
output
Termination:normal
Note: Hence length of try block should be as less as possible and take only risky code inside try block
Or go for multiple try block
CONTROL FLOW INTRY CATCH
Case 3: if there is an exception in statement 2 and corresponding catch not matched
CONTROL FLOW IN TRY CATCH
Case 3: if there is an exception in statement 2 and corresponding catch not matched
Order of execution
output
Termination:Abnormal
CONTROL FLOW INTRY CATCH
Case 4: if there is an exception in try as well as in catch statement or outside try statement
CONTROL FLOW IN TRY CATCH
Case 4: if there is an exception in try as well as in catch statement or outside try statement
Order of execution
output
Termination:Abnormal
NOTE:
1.With in the try block if anywhere an exception occur then rest of the
try wont be executed even though we handled that exception hence with
in the try block we have to take only risky code and length of try
block should be as less as possible.
2.In addition other than try block there may be chance of rising an
exception inside catch and finally blocks.
3.If any statement which is not part of try block and an exception occur
then it is always abnormal termination.
METHODS TO PRINT EXCEPTION INFORMATION
printStackTrace()
toString() getMessage()
TRYWITH MULTIPLE CATCH BLOCKS
Limitation
• Order of execution is very important when having multiple catch, because first
we will take child first and the parent exception, if we take parent exception
first and then child exception you will surely get a compilation error.
TRY WITH MULTIPLE CATCH BLOCKS
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block
The try block within a try block is known as nested try block in java.
output
JAVA FINALLY BLOCK
Finally block is used to perform clean-up activities that we related to try block , means
what ever resources we open in the try block will be closed inside finally block.
Java finally block is a block that is used to execute important code such as closing
connection, closing a file etc.
System.out.println(data);
} Note:
For each try block there can be zero or more
catch(ArithmeticException e){System.out.println(e);} catch blocks,but only one finally block.
finally{System.out.println("finally block is always exe
cuted");} The finally block will not be executed if program
exits(either by calling System.exit()
System.out.println("rest of the code..."); or by causing a fatal error that causes the process
} to abort).
}
THROW KEYWORD
Some times we can create exception object explicitly and handover the object
manually for which we use throw keyword.
Output:
Exception in thread main java.lang.ArithmeticException:not
valid
JAVA EXCEPTION PROPAGATION
An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method, If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they
reach the very bottom of the call stack. This is called exception propagation.
Note: the next line after throw exception will give us unreachable statement because compiler is aware
about that statement that it is not going to execute.
JAVA EXCEPTION PROPAGATION: EXAMPLE
class TestExceptionPropagation1{
void m(){
public static void main(String args[]){
int data=50/0;
} TestExceptionPropagation1 obj=new
void n(){ TestExceptionPropagation1();
m(); obj.p();
} System.out.println("normal flow...");
}
void p(){
}
try{
n();
}catch(Exception e){System.out.println("exception h
andled");}
}
OUTPUT
exception handled
normal flow...
CHECKED EXCEPTION
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("de public static void main(String args[]){
vice error");//checked exception TestExceptionPropagation2 obj=new TestExce
} ptionPropagation2();
void n(){ obj.p();
m();
System.out.println("normal flow");
}
}
}
void p(){
try{
n();
}catch(Exception e){System.out.printl
n("exception handeled");}
}
throws KEYWORD
error: beyond your control e.g. you are unable to do anything if there
occurs VirtualMachineError or StackOverflowError.
Example
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception }
void n()throws IOException{
m(); }
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");} }
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
} }
Example
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception }
void n()throws IOException{
m(); } OUTPUT
exception handled
void p(){ normal flow...
try{
n();
}catch(Exception e){System.out.println("exception handled");} }
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
} }
If you are calling a method that declares an exception, you must either caught or
declare the exception.
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
Case1:You handle the exception
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow..."); }}
Case1:You handle the exception
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
} OUTPUT:
exception handled
public class Testthrows2{ normal flow...
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow..."); }}
Case2:You declare the exception
import java.io.*;
class M{
void method()throws IOException{ OUTPUT:
device operation performed
System.out.println("device operation performed"); normal flow...
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
} }
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
} Output:
} Runtime Exception
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Difference between throw and throws in Java
No. throw throws
1) Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an
exception. exception.
2) Checked exception cannot be propagated using Checked exception can be propagated with throws.
throw only.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
Overview of Streams and File I/O
Text-File I/O
Using the File Class
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
it acts as a buffer between the data source and destination
Input stream: a stream that provides input to a program
System.in is an input stream
Output stream: a stream that accepts output from a program
System.out is an output stream
A stream connects a program to an I/O object
System.out connects a program to the screen
System.in connects a program to the keyboard
Binary Versus Text Files
All data and programs are ultimately just zeros and ones
each digit can have one of two values, hence binary
bit is one binary digit
byte is a group of eight bits
Text files: the bits represent printable characters
one byte per character for ASCII, the most common code
for example, Java source files are text files
so is any file created with a "text editor"
Binary files: the bits represent other types of encoded information, such as
executable instructions or numeric data
these files are easily read by the computer but not humans
they are not "printable" files
actually, you can print them, but they will be unintelligible
"printable" means "easily readable by humans when printed"
Java: Text Versus Binary Files
Text files are more readable by humans
Binary files are more efficient
computers read and write binary files more easily than text
Java binary files are portable
they can be used by Java on different machines
Reading and writing binary files is normally done by a program
text files are used only to communicate with humans
https://www.geeksforgeeks.org/compilation-execution-java-program/
PrintWriter FileOutputStream
Memory Disk
smileyOutStream smiley.txt
print
format
flush: write buffered output to disk
close: close the PrintWriter stream (and file)
TextFileOutputDemo
Part 1 A try-block is a block:
outputStream would
public static void main(String[] args)
{ not be accessible to the
PrintWriter outputStream = null; rest of the method if it
try were declared inside the
Opening the file { try-block
outputStream =
new PrintWriter(new FileOutputStream("out.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file out.txt. “
+ e.getMessage());
System.exit(0); Creating a file can cause the
}
FileNotFound-Exception if
the new file cannot be made.
TextFileOutputDemo
Part 2 System.out.println("Enter three lines of text:");
String line = null;
int count;
for (count = 1; count <= 3; count++)
{
line = keyboard.nextLine();
outputStream.println(count + " " + line);
}
outputStream.close(); Writing to the file
System.out.println("... written to out.txt.");
}
Closing the file
Opening an output file creates a new file if it does not already exist
Opening an output file that already exists eliminates the old file and creates
a new, empty one
data in the original file is lost
To see how to check for existence of a file, see the section of the text that
discusses the File class (later slides).
Java Tip: Appending to a Text File
To add/append to a file instead of replacing it, use a different constructor for
FileOutputStream:
outputStream =
new PrintWriter(new FileOutputStream("out.txt",
true));
Two reasons:
1. To make sure it is closed if a program ends abnormally (it could get
damaged if it is left open).
2. A file opened for writing must be closed before it can be opened for
reading.
Although Java does have a class that opens a file for both reading
and writing, it is not used in this text.
Text File Input
To open a text file for input: connect a text file to a stream for reading
Goal: a BufferedReader object,
which uses FileReader to open a text file
FileReader “connects” BufferedReader to the text file
For example:
BufferedReader smileyInStream =
new BufferedReader(new FileReader(“smiley.txt"));
Similarly, the long way:
FileReader s = new FileReader(“smiley.txt");
BufferedReader smileyInStream = new
BufferedReader(s);
Input File Streams
BufferedReader FileReader
Memory Disk
smileyInStream smiley.txt
read returns -1 when it tries to read beyond the end of a text file
the int value of all ordinary characters is nonnegative
Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 109
Using Path Names
Path name—gives name of file and tells which directory the file is in
Relative path name—gives the path starting with the directory that the
program is in
Typical UNIX path name:
/user/smith/home.work/java/FileClassDemo.java
Typical Windows path name:
D:\Work\Java\Programs\FileClassDemo.java
When a backslash is used in a quoted string it must be written as two
backslashes since backslash is the escape character:
"D:\\Work\\Java\\Programs\\FileClassDemo.java"
Java will accept path names in UNIX or Windows format, regardless of
which operating system it is actually running on.
File Class [java.io]
Acts like a wrapper class for file names
A file name like "numbers.txt" has only String properties
File has some very useful methods
exists: tests if a file already exists
canRead: tests if the OS will let you read a file
canWrite: tests if the OS will let you write to a file
delete: deletes the file, returns true if successful
length: returns the number of bytes in the file
getName: returns file name, excluding the preceding path
getPath: returns the path name—the full name
Scanner
nextInt(), nextFloat(), … for parsing types
BufferedReader
read(), readLine(), … none for parsing types
needs StringTokenizer then wrapper class methods like
Integer.parseInt(token)
BufferedReader vs Scanner
(Checking End of File/Stream (EOF))
BufferedReader
readLine() returns null
read() returns -1
Scanner
nextLine() throws exception
needs hasNextLine() to check first
nextInt(), hasNextInt(), …
BufferedReader inFile = …
line = inFile.readline();
while (line != null)
{
// …
line = inFile.readline();
}
-------------------
Scanner inFile = …
while (inFile.hasNextLine())
{
line = infile.nextLine();
// …
}
BufferedReader inFile = …
line = inFile.readline();
while (line != null)
{
// …
line = inFile.readline();
}
-------------------
BufferedReader inFile = …
while ((line = inFile.readline()) != null)
{
// …
}
My suggestion
Use Scanner with File
new Scanner(new File(“in.txt”))
Use hasNext…() to check for EOF
while (inFile.hasNext…())
Use next…() to read
inFile.next…()
Simpler and you are familiar with methods for Scanner
My suggestion cont…
File input
Scanner inFile =
new Scanner(new File(“in.txt”));
File output
PrintWriter outFile =
new PrintWriter(new File(“out.txt”));
outFile.print(), println(), format(), flush(), close(), …
Basic Binary File I/O
Important classes for binary file output (to the file)
ObjectOutputStream
FileOutputStream
Important classes for binary file input (from the file):
ObjectInputStream
FileInputStream
Note that FileOutputStream and FileInputStream are used only for
their constructors, which can take file names as arguments.
ObjectOutputStream and ObjectInputStream cannot take file
names as arguments for their constructors.
To use these classes your program needs a line like the following:
import java.io.*;
Java File I/O: Stream Classes
ObjectInputStream and ObjectOutputStream:
have methods to either read or write data one byte at a time
automatically convert numbers and characters into binary
binary-encoded numeric files (files with numbers) are not
readable by a text editor, but store data more efficiently
Remember:
input means data into a program, not the file
similarly, output means data out of a program, not the file
When Using ObjectOutputStream
to Output Data to Files:
The output files are binary and can store any of the primitive data types
(int, char, double, etc.) and the String type
The files created can be read by other Java programs but are not printable
Also note that each write method includes the modifier final
final methods cannot be redefined in derived classes
Closing a File
An Output file should be closed when you are done writing to
it
If a program ends normally it will close any files that are open
Writing a Character to a File: an Unexpected Little Complexity
For example, to write the character 'A' to the file opened previously:
outputStream.writeChar((int) 'A');
true and false are not just names for the values, they
actually are of type boolean
Input files are binary and contain any of the primitive data types (int, char,
double, etc.) and the String type
The files can be read by Java programs but are not printable
You can read data from an input file after it is connected to a stream class
Use methods defined in ObjectInputStream
readInt()
readDouble()
readBoolean()
etc.
See the text for more
Also note that each write method includes the modifier final
Input File Exceptions
In these situations you need to check for the end of the file
There are three common ways to test for the end of a file:
1. Put a sentinel value at the end of the file and test for it.
2. Throw and catch an end-of-file exception.
3. Test for a special character that signals the end of the file
(text files often have such a character).
The EOFException Class
Many (but not all) methods that read from a file throw an end-of-file exception
(EOFException) when they try to read beyond the file
all the ObjectInputStream methods in Display 9.3 do throw it
Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 144
Binary I/O of Class Objects
read and write class objects in binary file
ClassIODemo Excerpts
inputStream = new ObjectInputStream(
new FileInputStream("species.records"));
... readObject returns a reference to
Species readOne = null; type Object so it must be cast to
... Species before assigning to readOne
readOne = (Species)inputStream.readObject(oneRecord);
The Serializable Interface
Java assigns a serial number to each object written out.
If the same object is written out more than once, after the
first write only the serial number will be written.
When an object is read in more than once, then there will be
more than one reference to the same object.
If a serializable class has class instance variables then they should
also be serializable.
Why aren't all classes made serializable?
security issues: serial number system can make it easier for
programmers to get access to object data
doesn't make sense in all cases, e.g., system-dependent data
Summary
Part 1
Text files contain strings of printable characters; they look
intelligible to humans when opened in a text editor.
Binary files contain numbers or data in non-printable codes; they
look unintelligible to humans when opened in a text editor.
Java can process both binary and text files, but binary files are
more common when doing file I/O.
The class ObjectOutputStream is used to write output to a
binary file.
Summary
Part 2
The class ObjectInputStream is used to read input from a
binary file.
Always check for the end of the file when reading from a file. The
way you check for end-of-file depends on the method you use to
read from the file.
A file name can be read from the keyboard into a String
variable and the variable used in place of a file name.
The class File has methods to test if a file exists and if it is read-
and/or write-enabled.
Serializable class objects can be written to a binary file.
THANK YOU
?