Exception Handling & IO
UNIT 5
EXCEPTION HANDLING FUNDAMENDALS
✔ An exception is an abnormal condition/event that occurs during
execution of a program.
✔ It disrupts the normal flow of the program/application & the
program/application terminates abnormally.
✔ When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error.
✔ In java, exception handling is a mechanism that handles runtime
errors so that normal flow of the program can be maintained.
✔ Exceptions are said to be raised or thrown at the point of
interruption and are said to be handled or caught at the point when
normal execution resumes.
✔ Exceptions can be of any type, runtime exception(unchecked),
compile-time(checked) exception or error exceptions.
Reasons for occurance of exceptions
• User error – for example if aa user has entered invalid data.
• Programmer error – for example a file that needs to be opened and
cannot be found.
• Failure of physical resources – for example a network connection that
has been lost in the middle of communications or the JVM has run
out of memory.
Unchecked exceptions
❖ An unchecked exception is an exception that occurs at the time of
excecution & that probably could have been avoided by the
programmer.
❖ They are also called runtime exceptions.
❖ As opposed to checked exceptions, runtime exceptions are ignored at
the time of compilation, these include programming bugs, such as
logic errors or improper use of an API.
❖ For example, if you have declared an array of size 5 in your program,
and trying to call the 6th element of the array then an
ArrayIndexOutOfBoundsException exception occurs.
Checked exceptions
❖ Are exceptions that occur at compile time hence they are also called
compile-time exceptions.
❖ A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer.
❖ For example if you use FileReader class in your program to read data
from a file, if the file specified in the constructor does not exist, then
an FileNotFoundException occurs and compiler prompts the
programmer to handle the exception.
Errors
❖ These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer.
❖ Errors are typically ignored in your code because you can rarely do
anything about an error.
❖ For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
❖ Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionErroretc.
❖ Errors are not normally trapped form the Java programs. These
conditions normally happen in case of severe failures, which are not
handled by the java programs. Errors are generated to indicate errors
Checked and unchecked exceptions
Checked exceptions Unchecked exceptions
• Checked at compile time. • Handling not verified during
compile-time.
• If a method throws a checked • These exceptions are handled at
exception, then the method runtime ie by JVM after they
must either handle the occurred by the try and catch
exception or it must specify the block.
excecution using the throw
keyword. • Eg NullPointer, ArrayIndexOut,
• Eg IO, SQL, DataAccess, IIIegalArgument & IIIegalState
ClassNotFound, exceptions.
Exception hierarchy
• All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than
the exception class there is another subclass called Error which is
derived from the Throwable class.
• The Exception class has two main subclasses: IOException class and
RuntimeException Class.
General form of an exception handling block
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
Terms in the general form of an exception
handling block
• try block contains program statements that are to be to monitored
for exceptions
– If an exception occurs within the try block, it is thrown
• catch block contain statements that catch this exception and handle
it in some rational manner
– System-generated exceptions are automatically thrown by the Java
runtime system.
• throw is used to manually throw an exception
• throws clause is used to specify any exception that is thrown out of a
method
• finally block contains code that absolutely must be executed after a
Program examples
1. Using try and catch
2. Multiple catch clauses
3. Nested try statements
4. Using throw
5. Using throws
6. Using finally
Uncaught exceptions
• Uncaught exception :caught by the default handler (provided by the
Java run-time system) that
– displays a string describing the exception
– prints a stack trace from the point at which the exception occurred
– terminates the program
MULTITHREADING
• Multithreading in java is a process of executing multiple threads
simultaneously.
-A thread is a lightweight sub process, a smallest unit of processing.
It is a separate path of execution.
-Threads are independent, if there occurs exception in one thread,
it doesn't affect other threads. It shares a common memory area.
• We use multithreading than multiprocessing because threads share a
common memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less
time than process.
• Java Multithreading is mostly used in games, animation etc
THREADS(lightweight sub-processes)
THREADS AND MESSAGING
Java provides a clean, low-cost way for two or more threads to talk to
each other, via calls to predefined methods that all objects have. Java’s
messaging system allows a thread to enter a synchronized method on
an object, and then wait there until some other thread explicitly
notifies it to come out.
LIFE CYCLE OF A THREAD
1) New - The thread is in new state if you create an instance of Thread
class but before the invocation of start() method.
2) Runnable - The thread is in runnable state after invocation of start()
Lifecycle of a thread…
Methods involved in thread processes
• Suspend() & resume() methods
-this approach is useful when we want to suspend a thread for some
time due to a certain reason, but do not want to kill it.
• Sleep() method
-this means that the thread is out of the queue during this time period.
The thread then re-enters the runnable state as soon as this period has
elapsed.
• Wait() & notify() methods
-blocked until certain condition occurs.
• Yield() method
-used to release control
isAlive() & join() methods
isAlive()
The isAlive( ) method returns true if the thread upon which it is called is
still running. It returns false otherwise final boolean isAlive( )
join()
This method waits until the thread on which it is called terminates. Its
name comes from the concept of the calling thread waiting until the
specified thread joins it.
Additional forms of join( ) allow you to specify a maximum amount of
time that you want to wait for the specified thread to terminate. final
void join( ) throws InterruptedException
Common methods of thread class
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number
of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
How to create a thread
There are two ways to create a thread:
1. By extending Thread class.
2. By implementing Runnable interface.
• Thread class: Thread class provide constructors and methods to
create and perform operations on a thread. Thread class extends
Object class and implements Runnable interface.
• Runnable interface: The Runnable interface should be implemented
by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
How to create a thread…
Java Thread Example by extending Java Thread Example by implementing
Thread class Runnable interface
Thread priorities
• Thread priorities are used by the thread scheduler to decide when
each thread should be allowed to run.
• In practice, the amount of CPU time that a thread gets often depends
on several factors besides its priority. (For example, how an operating
system implements multitasking can affect the relative availability of
CPU time.)
• A higher-priority thread can also preempt a lower-priority one. For
instance, when a lower-priority thread is running and a higher-priority
thread resumes (from sleeping or waiting on I/O, for example), it will
preempt the lower priority thread.
Thread priorities…
2. setPriority()
To set a thread’s priority, use the setPriority( ) method, which is a
member of Thread.
This is its general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and
MAX_PRIORITY. Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which
JAVA I/O
• The core for part used for processing input and producing output.
• Java.io package contains all the classes needed for input and output
• Java uses a stream to make IO operations faster, where a stream is a
sequence of data
• 3 stream provided by java include System.out, System.in, System.err
JAVA I/O
● System.out.println(“output a Message”);
● System.out.err(“Output an Error”);
● System.in is passed into a scanner in order to receive user input
● Scanner input = new Scanner(System.in);
● OutputStream – used to write data to some destination eg a file,
example of this will be elaborated in the serialization part of this
presentation
● InputStream – uses input sream to read data from source
Programs for:
• Serializing an object
• Deserializing an object
• Serialization with inheritance
• Serialization with agreggation
• Serialization with the static data member
• Serialization with array or collection
JAVA SERIALIZATION
• Serialization in Java is a mechanism of writing the state of an object
into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and
JMS technologies.
• For serializing the object, we call the writeObject() method
ObjectOutputStream, and for deserialization we call the readObject()
method of ObjectInputStream class.
• We must have to implement the Serializable interface for serializing
the object.
Advantages of Java Serialization
• It is mainly used to travel object's state on the network (which is
known as marshaling).
Java serialization…
1. Serializing an object - The ObjectOutputStream class is used to
serialize an Object. When serializing an object to a file, the standard
convention in Java is to give the file a .ser extension.
2. Deserializing an object - The try/catch block tries to catch a
ClassNotFoundException, which is declared by the readObject()
method. For a JVM to be able to deserialize an object, it must be
able to find the bytecode for the class. If the JVM can't find a class
during the deserialization of an object, it throws a
ClassNotFoundException.
java.io.Serializable interface
• Serializable is a marker interface (has no data member and method).
It is used to "mark" Java classes so that the objects of these classes
may get a certain capability. The Cloneable and Remote are also
marker interfaces.
• It must be implemented by the class whose object you want to
persist.
• The String class and all the wrapper classes implement the
java.io.Serializable interface by default.
• Example:
import java.io.Serializable;
public class Student implements Serializable{
int id;
Following screenshots in following order
● Exceptions => 2
● Threads => 2
● Serializer => 2
Exception Handling by example
Output of the serialized video.ser file