Object Oriented Programming with Java
AKTU Unit :- 2 BCS-403
Exception Handling
Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of Exception, Control
Flow in Exceptions, JVM Reaction to Exceptions, Use of try, catch, finally, throw, throws in
Exception Handling, In-built and User Defined Exceptions, Checked and Un-Checked Exceptions.
An exception is something that is left out or not done on
purpose. An exception to a rule does not follow that rule.
In Java “an event that occurs during the execution of a
program that disrupts the normal flow of instructions” is called an
exception. This is generally an unexpected or unwanted event which
can occur either at compile-time or run-time in application code.The Idea Behind Exceptions
‘An exception usually signals an error and isso called because errors in your Java programs are bound to be the exception rather
than the rule—by definition! An exception doesn't always indicate an error thought can also signal some particularly unusual
event in your program that deserves special attention
If you try to deat with the myriad and often highly unusual error conditions that might arse in the midst of the code that deals
With the normal operation of the program, your program structure will soon become very complicated and difficult to understand,
‘One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code
that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of en:
forcing a response to particular errors. With many kinds of exceptions, you must include cade in your program to deal with them;
otherwise, your code will not compile
« cxenton YG ever )
Errors V/s Exceptions v
In Short errors and exceptions represent different types of problems that
can occur during program execution. Errors are usually caused by serious
problems that cannot be recovered from, while exceptions are used to
handle recoverable errors within a program.Types of Exception
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.
Exceptions can be categorized into two ways
1. Built-in Exceptions
© Checked Exception
© Unchecked Exception
2. User-Defined Exceptions
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
* Opening an unavailable fileException Hierarchy
All exception and error types are subclasses of the class Throwable, which is
the base class of the hierarchy. One branch is headed by Exception. This class
is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception. Another branch, Error
is used by the Java run-time systemUVM) to indicate errors having to do with
the run-time environment itself URE). StackOverflowError is an example of such
an error,
publi state void main(String args)
in datas500,//may trow exception
‘jtemoutprinin est ofthe code
Control Flow in Exceptions
publi clas TCatchExampe
ava, Lane Arithmeticeiception: / by 26F8JVM Reaction to Exceptions
The JVM starts the search from the method where the exception
occurred and then goes up the call stack, checking each method in
turn for a catch block that can handle the exception. If a catch block
is found, the JVM transfers control to that block and the exception is
considered to be handled.Exception Handling
In Exception handling , we should have
an alternate source through which we
can handle the Exception.
Advantage of Exception Handling
‘The core advantage of exception handling is to maintain the normal flow of the application, An exception
normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider
statement Suppose there are 10 statements ina Java program and an exception occurs at statement §; the rest of the
statement 2 code will not be executed ie, statements 6 to 10 will not be executed. However, when we perform exception
statement 3 handling, the rest ofthe statements will be executed. Thats why we use exception handing in Java.
one
statement S//exception occurs Java Exception Keywords
=
|
aces
statement 9lic class TyCatchbcampe
Java uses keyword “try” to preface a block of code that is likely to ee eee
‘cause an error condition and “throw” an exception.
whe state vld main tng os
‘The try block can have one or more statements that could generate cE al
ty
an exception. :
try = int data=50/0; /may throw exception
{ d
statement ; // generates an exception ‘handing the exception
}
2
> sfend of ery
eaten (tyexceptton «) ¢ Runtime Error
printstacktrace(); MEKCEPon Balance is 1ess\than 000
> a8 ytaception ain fleoreperty. ja
Detalts of account numbers, customer names, and balance amounts are
taken inthe form of thee arays
In. maing) method, the details are displayed using a forloop. At this time, a
check s done iin any account the balance amount is less than the minimum
balance amount tobe apt in the account
titi so, then MyException is raised and » message is displayed “BalanceInput / Output Basics
Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java.
File 10
In Java, we can read data from files and also write data in files.
We do this using streams. Java has many input and output streams that are used to
read and write data. Same as a continuous flow of water is called water stream, in the
same way input and output flow of data is called stream.
Stream
Java provides many input and output stream classes which are used to read and write.
Streams are of two types. A atts Sa
* Byte Stream
* Character Stream
‘These streams can be different in how they are handling data and the type of data they are handlingByte Streams:
Byte streams are designed to deal with raw binary data, which includes al kinds of data, including characters,
pictues, audio, and video. These streams are represented through cclasses that cease with the word
“InputStream’ or "OutputStream" of their namesalong with FilelnputStream BufferedinputStream,
FileOutputStream and ButferedOutputStream.
Byte streams offer a low-stage interface for studying and writing character bytes or blocks of bytes. They are
normally used for coping with non-textual statistics, studying and writing files of their binary form, and
running with network sockets. Byte streams don't perform any individual encoding or deciphering, They treat
the data as a sequence of bytes and don't interpret it as characters.
Character Streams:
Character streams are designed to address character based records, which includes textual records inclusive
Of letters, digits, symbols, and other characters. These streams are represented by way of training that quit
with the phrase "Reader" or “Writer” of their names, inclusive of FileReader, BufferedReader, FileWriter, and
BufferedWriter.
CCharacter streams offer a convenient manner to read and write textual content-primarily based information
due to the fact they mechanically manage character encoding and decoding. They convert the individual
statistics to and from the underlying byte circulation the usage of a particular individual encoding, such as
UTF-eight or ASCILIt makes person streams suitable for operating with textual content files, analyzing and
writing strings, and processing human-readable statistics.Classes —
‘Byte Stream Character
‘lasses
co
Taput stream os
Byte Stream Classes: ioe
8 bts car
‘OutputStream —
py chews
InputStream
: OutputStream Fig Cascaion ova Stream Classes
BurferedinputStream -BurferedOutputStream
Byterayinpustream ByteArrayOutputStream
Datanpusteam DataOutputStream
‘Objectnput Stream" -ObjectOutputStream.
FleinputStream FleOutputStream
PipedinputStream PipedOutputStream ou
InputStream Qutputstream
FilterinputStream nputsieam —_ E-BaterOutputstream. outputs
RggtStroam tt) pte
“roa an wrt bah ry methods fy teamExample code for Byte Stream:
Import jaaio ByteArayinputvear
Public clas BjteSteaméxample
‘i
publi state void maining) args)
(
1) Creates teary fs
byte) ray = (19203040
wt
BjedraynputSteam inpt-new Byteieraynputtveamiany)
‘Sjtemout prin The bytes read am the np rea
forint =0caraylengthie)
1
1 Reads te bytes
Int datasinputread
Sjtem out priate)
)
inputcose
cate Exception eo)
canst oxo
) ‘he bytes read from the input strean:ie,22, 30,48
)
Example code for Character Stream:
Import jnaiaCharrayReader,
Import jaialOEscepton:
‘public les CharecterSveamExanpe
1
publi state vod mating aa (
1) Coates an ary of characters
char aay = (46/0
wy!
‘CharrayReader eadersmew CharkrayReadearay
‘ystemoutpint( The characters ead from the reader"
int chorea
while (charead=readerread)!=-1){
Sytem out print charicharead
1
reader ose
catch (OEscepione)
‘exprinstackracey
, output
’
‘ihe characters read from the readerstye,1u1.0,Reading from a file:
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
Reading and Writing File in Java
1. In Java, the FilelnputSream class is used for reading binary data
from a file.
2. Itis an input stream that reads bytes from a file in a file system.
3.To read data from a file using FilelInputStream, these steps you
need to follow :-
Create an instance of the FilelnputStream class and pass the path of the file that you
want to read as an argument to its constructor.
Create a byte array of a fixed size to read a chunk of data from the file.
Use the read() method of the FilelnputStream class to read data from the file into the
byte array. This method returns the number of bytes read , or -1 if the end of the file
has been reached.
Continue reading data from the file until the read() method returns -1.
Close the FileInputStream object using to release the close() method to release any
system resources associated with it.Following example demonstrates how to use Fileinputstream
to read data from a file :
import java.io.*
ublic class ReadFileExample { Inthe emplelevove WoC oa
Oe eee PI FilelnputStream object to read data
public static void main(String[] args) { fee teadiel eke
try{ .
Enélnputstreamm fleinput. new We then create a byte array of size 1024
FilelnputStream ("file.txt"); y y
Pennine Fee een, to read a chunk of data from the file.
int bytesRead = 0;
while ((bytesRead = filelnput.read(buffer))!=-1){
System.out.printIn/new String buffer, 0, bytesread));
} We use the read() method to read data
filetnput.close(); into the buffer untill the end of the file is
} catch (IOException e) { reached, and then we close the
e.printStackTrace(); FilelnputStream object.
} Finally, we print the data that we read
} from the file to the consoleWriting in a file: 1. In Java, FileQutputStream class in used for writing binary data to a file.
2. Itis an output stream that writes bytes to a file in a file system.
3. To write data to a file using FileOutputStream, you need to follow
these steps:
Step 1: Create an instance of the FileOutputStream class and pass the path of the file that
you want to write as an argument to its constructor. If the file dosen't exist, it will
be created automatically.
‘Step 2: Create a byte array that contains the date that you want to write to the file.
Step 3: Use the write() method of the FileOutputStream class to write the data to the File
This method writes the entire array to the the file.
Step 4: Close the FileOutputStream object using the close() method to release any system
resources associated with it.
Following example demonstrates how to use FileOutputstream
to write data to a file :import java.io.*;
public class Write File Example {
public static void main(String[] args) {
try {
FileOutputStream fileOutput = new
FileOutputStream(‘ile.txt");
String data ="This is some data that will be written to a file";
byte{] bytes = data.getBytes();
fileOutput. write(bytes);
fileQutput. close();
} catch (IOException e) {
e.printStackTrace();
}
} We convert this string to a byte array using the getbytes()
method and then we use the write() method to write the
data to the file,
In the example above, we create a FileOutputStream
object write data to a file called "file.txt".
We then create a string that contains some data that we
wants write to the file.
Finally, we close the FileOutputStream object.Multithreading
Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread Priorities, Synchronizing
Threads, Inter-thread Communication.
MULTI THREADING IN JAVA
Multithreading in java is a process of executing multiple threads
simultaneously. Thread is basically a lightweight sub-process, a smallest
unit of processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception
occur in a single thread.What is Thread in java
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.
Life eyele of a Thread (Thread States) Anstagram
+ New _~
Runnable L@@
Seka —_
. Non-Runnable (Blocked)
. Terminated ce
BRON
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5
states.
The life cycle of the thread in java is controlled by JVM.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 seat)
a
‘The thread is in runnable state after invocation of start() method, but the
steep done. VO
“ompleteockvaaie,
cone,neehy
thread scheduler has not selected it to be the running thread. _— a
3) Running
‘The thread is in running state ifthe thread scheduler has selected it fy
4) Non-Runnable (Blocked) a al
This is the state when the thread is still alive, but is currently not eligible to = ae
—
5) Terminated
A thread is in terminated or dead state when its run() method exits
sleep, tckon0 wait
foro spend, waitHow to create thre:
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.
‘Commonly used Constructors of Thread class:
© Thread() © Thread(Runnable )
© ThreadiString name) © Thread(Runnable rString name)
Commonly used methods of Thread class:
1. public void rund)
is used to perform action fora thread,
2. public void startQ: starts the execution of the thread JVM cals the run) method on the thread.
3, public void sleeptlong miliseconds): Causes the currently executing thread to sleep (temporeriy
cease execution) forthe specified number of milliseconds.
4, public void join): waits fora thread to die
5. public void join(long miliseconds): wats fora thread to die fr the specified miiseconds.15
6
”,
18
9
20.
a
22.
Public int getPriority(): retums the priority of the thread.
public int setPriority(int priority): changes the priority ofthe thread
public String getName(): returns the name of the thread.
public void setName(String name): changes the name ofthe thread,
public Thread currentThread() returns the reference of currently executing thread.
public int getld(): returns the id ofthe thread,
public Thread State getState(): returns the state of the thread
public boolean isAlive() tests ifthe thread is alive
public void yield): causes the currently executing thread object to temporarily pause and allow other
threads to execute
public void suspend: is used to suspend the thread{depricated)
public void resume(
used to resume the suspended thread(depricated)
public void stop() is used to stop the thread{depricated)
public boolean isDaemon(): tests if the thread is a daemon thread.
publi void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(: interrupts the thread
public boolean isinterrupted() test ifthe thread has been interrupted
public static boolean interrupted() tests if the current thread has been interrupted.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,
Starting a thread:
‘The start) method of Thread class is used to start a newly created thread. It performs the following tasks:
© Anew thread starts(with new callstack)
© The thread moves from New state to the Runnable state
‘© When the thread gets a chance to execute, its target run() method will un
1) Java Thread Example by extending Thread class lass Multi extends Thread{
public void rund{
‘System out println( thread is running...)
5 output
FileName: Multijava public static void main(String args}
Multi tt=new MultiQ:
tistart);
}
f2) Java Thread Example by implementing Runnable interface
lass Mult implements Runnable
publi void rin
Systemoutprintnc head is runing.
1
output:
public static void main(String arth
Muti mt =new Muti
Thweadt enew Thread // Using the constructor TreadRunnabl
‘stant
’
‘enrend 6s running
I you are not extending the Thread class, your class object would not be treated as a thread object. So you
need to explicitly create the Thread class object. We are passing the object of your class that implements
Runnable so that your class run() method may execute
3) Using the Thread Class: Thread(String Name)
We can directly use the Thread clas to spawn new threads using the constructors defined above
ble clas MyTIveadt
(
11 Maio menos‘Public static void mainString argv)
1
1
U/ sin river method
public static void main(String{] args)
4
11 Creating randon threads
11 with the help of above class
‘Treaddeno ti » new Threaddeno();
‘TrrendDeno £2 = new Threaddeno();
‘Treaddeno £3 + new Threaddeno();
11 Thread 2
1/ splay the priority of above theese
1/ using getPriority() method
systen.out.printin("ti thread priority
eaigeterforsey())s
system.out.printin(“t2 thread priority ©
4 s2ugetrgorsty())s
U1 Tareas 3
System.out.printin("*3 thread priority
+ ea.getPrtorsty(0)5
11 Setting priorities of above threads by
11 passing integer argonent
ta.seterdority(2)s
talaetPriority(3)s
ta.setPriority(@);
“
uw
ts.setpriority(21); will throw
Tilegalargunentexception
wa
systen.out.printin("ti thread priority
+ ehagetrréority())5
us
system.out.printin(“t2 thread priority ©
+ e2igetPrdorsty())s
ue
systen-out.printin("t3 thread priority
+ s.getPrdority0)
1) Wa theese
1/ Displays the nane of
1) corrently executing Thread
= systen.cut.prinein¢
“currently fxecuting Thread : "
+ Theend.currentTareag)gettne())5
+ systen-out.printin¢
“hain theese préorsty
+ Threae.currentTaread() getoriority());
11 Rain thread pricrity is set to 10
‘Thread. currentThrend()-setPetalty(10);
‘ysten.out-printin¢
hain threes priarsty ¢ *
+ theeae.currentTaread().getoriority());
>
?
~ Output
tH thread priority : 5
42 thread priority +
43 thread priority
‘1 thread priority
42 thread priority +
43 thread priority : 8
‘currently Executing Thread ¢
Main thread priority : 5
Main thread priority : 10Synchronization in Ji
Synchronization in java is the capability to control the access of multiple
threads to any shared resource.
Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
Why use Synchronization
‘The synchronization is mainly used to
1, To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
‘There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
JAVA CONCURRENCY
SynchronizedThread Synchronization
There are two types of thread synchronization mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or
monitor. Every object has an lock associated with it. By convention, a thread
that needs consistent access to an object's fields has to acquire the object's
lock before accessing them, and then release the lock when it's done with
them.From Java 5 the package java.util.concurrent.locks contains several lock
implementations.
1. //example of java synchronized method
2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int ie1si<=53i+4)t yor Thre
5. System.out.printin(n*i); a
6. tryt % es
7. Thread,sleep(400); 7. ee
8. _jeatch(Exception e}(System.out. printin(e) ee
Bo ) 29. public void run(}{
. , 30. tprintTable(100);
-? a}
eS } oa)
14. class MyThread1 extends Thread me ye
1 fees nee ot 35. public static void main(String args|)){
= @ 36. Table obj = new Table();//only one object
me 37. MyThreadi t1=new MyThread1 (obj);
19. public void run(} ee
20. tprintTable(5); 40. t2'start)):
2} = ee
22. a2}
23. )Inter-thread communication in Java
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is @ mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executedit is
implemented by following methods of Object class:
+ wait() =e
+ notify() Drees)
+ notifyAll() | al
Tees) — (Ga
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
public final void wait()throws interruptedException Itwaits until object is notified.
public final void waitflong timeout)throws InterruptedException It waits for the specified amount of time.2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax: lic final void notify)
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread
Class? It is because they are related to lock and object has a lock.
Difference between wait and sleep?
“The wait) method releases the lock. ‘The sleep() method doesn't release the lock.
Iti a method of Object class Iie a method of Thread caee
Itis the non-static method leis the static method
It should be notified by notify) or notifyAll) After the specified amount of time, sleep is
methods completedUnderstanding the process of inter-thread communication
Entry Set The Owner Wait Set
Jwatin tobe net
vies -@ @
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wat() method on the object. Otherwise it releases the lock
and exits
4. If you call notfy() or notifyAll method, thread moves to the notified state (runnable state)
5. Now thread is available to acquire lock
6. After completion of the task, thread releases the lock and exits the monitor state of the object.Example of Inter Thread Communication in Java
class Customer
int armount=10000;
-gmnchronized void withdraw(nt amourt{
‘Systemoutprntn( going to withdraw.)
if(thisamountcamount}
‘Systemoutprntin( Less balance; waiting for deposit."
‘ry(wait(Jeateh(Exceptione))
)
this amount-=amount:
‘Systemoutprintin( withdraw completed.”
)
synchronized void deposit{int amount)
‘System outprintin("going to deposit.)
this amount + =amount;
‘System outprintin(‘deposit completed...
notify0;
)
)
class Test(
public static void main(String args)
final Customer c=new Customer)
ee
public void run()(c.withdraw(15000);) —
}start0;
a wisn
ese aman
deposit completed.
withdraw completed
»