Académique Documents
Professionnel Documents
Culture Documents
CH-4
EXCEPTION
An exception (or exceptional event) is a problem that arises during theexecution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore these
exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where
exception occurs.
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these we have three categories of Exceptions you need to understand them to know
how exception handling works in Java,
1. Checked exceptions: A checked exception is an exception that occurs at the compile
time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored at the time of compilation, the Programmer should take care of (handle)
these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the
file specified in its constructor doesn't exist, then anFileNotFoundException occurs, and
compiler prompts the programmer to handle the exception.
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.
many
subclasses
like
IOException,
RuntimeException,
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks like
the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
a). The code which is prone to exceptions is placed in the try block, when an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.
b). A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
c). The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
d). The finally block
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644
The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks
User-defined Exceptions:
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException
class.
BLOCK-3
CH-1
MULTI-THREADING
THREAD
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. Thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
MULTI-THREADING
Multithreading is a process of executing multiple threads simultaneously. A multi-threaded
program contains two or more parts that can run concurrently and each part can handle
different task at the same time making optimal use of the available resources specially when
your computer has multiple CPUs. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Ready: When a thread is created, it doesnt begin executing immediately. We must first
invoke start() method to start the execution. The thread is ready for execution.
Running: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Sleep: A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or
when the event it is waiting for occurs.
Terminated ( Dead ): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
CREATING THREADS
In Java, a thread can be created in 2 ways:
i)
Implementing Runnable interface
ii)
Extending Thread Class
Both of these reside in Java.lang package.
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644
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().
public void run(): is used to perform action for a thread.
Thread(String name)
Thread(Runnable r)
11.
12.
13.
14.
public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15.
16.
17.
18.
19.
20.
21.
22.
public static boolean interrupted(): tests if the current thread has been
interrupted.
THREAD PRIORITIES
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY
(a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and very much platform dependent.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
INTER-THREAD SYNCHRONIZATION
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issue. For example if multiple threads try to write within a same
file then they may corrupt the data because one of the threads can overrite data or while
one thread is opening the same file at the same time another thread might be closing the
same file.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized methods & synchronized statements.
Synchronization provides a simple monitor facility that can be used to provide the mutual
exclusion between java threads.
SYNCHRONIZED METHODS: These are used to coordinate access to objects that are
shared among multiple threads. These methods are declared with the synchronized
keyword. Only one synchronized method can be invoked at a time. When a synchronized
method is invoked for a given object, it acquires a lock for that object. In this case no other
synchronized method may be invoked for that object until the lock is released. This keeps
synchronized methods in multiple threads without any conflicts with each other. A lock is
automatically released when the method completes it execution & returns.
SYNCHRONIZED STATEMENTS: An effective means of achieving synchronization is to
create synchronized methods with in the class. But it will not work in all cases, for example,
if you want to synchronize access to objects of a class that was not designed for
multithreaded programming or the class that doesnt use synchronized methods. In this
situation, the synchronized statement is a solution.
Synchronized statement iused to acquire a lock on an object before performing an action. It
is applied on a statement block rather than an entire method.
INTER-THREAD COMMUNICATION
Inter thread communication is important when you develop an application where two or
more threads exchange some information.
There are simply three methods which makes thread communication possible.
RADIANT SOFTWARE SYSTEM- NO.1 INSTITUTE FOR IGNOU BCA/MCA
COACHING
ADDRESS- D9, GOEL COMPLEX, LAXMI NAGAR DELHI-92 NEAR SAI TEMPLE ,
METRO PILLAR -34
MOB- 9871030624, 9999161644
These methods have been implemented as final methods in Object, so they are
available in all the classes. All three methods can be called only from within
a synchronized context.