Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

SCHOOL OF ARTS AND SCIENCE

DEPARTMENT OF COMPUTATIONAL
STUDIES
UNIT-III
PROBLEM SOLVING USING JAVA
(A20CPT305)

Dr. ANTONY PAUL RAJ.A M.Sc., M.Phil., B.Ed., Ph.D


Assistant Professor
Department of Computational Studies
School of Arts and Science, SMVEC
UNIT III

EXCEPTION HANDLING AND MULTITHREADING

Concepts of Exception handling – Types of exceptions – Creating own


exception – Concepts
of Multithreading – creating multiple threads – Synchronization – Inter
thread
communication. Enumeration: Auto boxing – Generics.
CONCEPTS OF EXCEPTION HANDLING

An exception is that unwanted or an unexpected event that disturbs normal flow


of a program is called as ―exception‖.

Eg: file not found, arithmetic exception, stack overflow, null pointer, number
format exception
etc.
When we write any program in any programming language, we get the following
errors in types of situations.

i. Compile tim]e occur when you do not follow the syntax of a programming
language

ii. Run errors occur during the execution of a program


Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:

TYPES OF EXCEPTION:
1. Checked exception.
2. Unchecked exception.
3. Error.
Checked exceptions:
Checked exceptions are those exceptional conditions that are checked by compiler at the compile time.
A checked exception forces you to either use try-catch or throws. All exceptions except Error, RuntimeException,
and their subclasses are checked exceptions.
e.g. – IOException, SQLException etc.

Unchecked exceptions:
Unchecked exceptions are those exceptional conditions that are not checked by compiler at the compile time.
Unchecked exceptions are checked at runtime. An unchecked exception not forces you to either use try-catch or
throws. RuntimeException and their subclasses are unchecked exceptions. This Exception can be avoided by
programmer.
e.g. – NullPointerException, ArithmeticException etc.

Error:
Errors are those exceptional conditions that are not checked by compiler at the compile time. Errors are checked at
runtime. An error not forces you to either use try-catch or throws. Error and their subclasses are represents errors.
Error can’t be avoided by programmer, it is irrecoverable.
e.g. – OutOfMemoryError etc.
EXCEPTIONAL HANDLING
MECHANISMS:
USING TRY AND CATCH
The try/catch statement encloses some code and is used to handle errors and
exceptions that might occur in that code. With the help of try and catch we solve
the run time error easy. The general syntax of the try/catch statement is as below:
Example:
MULTIPLE CATCH CLAUSES
When an exception is thrown, each catch statement is inspected in order. The first catch block whose type
matches is executed. After one catch statement executed, the others are bypassed & executed continues after
try-catch block. At that time we use multiple catch
FINALLY
Java support another statement known as finally statement that can be used to handle an exception that is not
caught by any of the previous catch statements. Finally block can be used to handle any exception generated within
a try block.
It may be added immediately after the try block or after the last catch block shown as follow. When a finally block
is defined, this is guaranteed to execute, regardless of whether or not in exception is thrown. As a result, we can
use it to perform certain house-keeping operations such as closing file and releasing system resource.
Syntax:
try
{
// statements
}
catch (<exception> obj)
{
// statements
}
finally
{
//statements
}
DIFFERENCE BETWEEN FINAL, FINALLY, FINALIZE:

• Final:
final is a keyword which can be used to declare anything as constant. Final keyword is utilized in
following ways.
1. Final variable→not to change its value (making variable as constant).
2. Final method→not to override the implementation.
3. Final class→not to extend.

• Finally:
Finally is a clause in try-catch syntax which can be used to execute a block of instructions irrespective of getting
exception in try block, irrespective of getting exception in catch block.

• Finalize:
Finalize is a method of object class which is used for making an object eligible for garbage collection.
THROW
A throw keyword is that which is used to create an exception object explicitly either for predefined or
user defined
In general java applications we get exceptions automatically when we have exception situations in java
app’s
If we want raise an exception explicitly we have to use throw keyword to raise an exception explicitly
by a programmer. We have to use following syntax.

Syntax:
throw new Exception_class([parameter_list]);
CREATING OWN EXCEPTION

In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception. Basically,
Java custom exceptions are used to customize the exception according to user need.

STEPS TO CREATE USER DEFINED EXCEPTION:


1. To create user defined exception, we have to create user defined class i.e. subclass to the
exception class.
2. To create user defined exception, define a custom exception class which has to be extend from
extended class.

class InvalidException extends Exception


{
}
3. Declare an string parameterized constructor and access the super class i.e. exception class
string parameterized constructor by using super keyword.
MULTITHREADING
INTRODUCTION

The program in execution is called "Process". The program can be


structured as set of individual units that can run in parallel. These units
can be called as "Threads". Multithreading is actually a kind of
multitasking. The multitasking is either process-based or thread base.
Process-based multitasking is nothing but, execution of more than one
program concurrently. Thread-based multitasking allows more than
one thread within the program run simultaneously or concurrently.
Thread
A thread is a lightweight subprocess, the 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 uses a shared memory area
Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking. However, we use multithreading than
multiprocessing because threads use a shared 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.

LIFE CYCLE OF A THREAD (THREAD STATES)


The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
 New
 Runnable
 Running
 Non-Runnable (Blocked)
 Terminated
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() method, but the thread scheduler has
not selected it to be the running thread.

3) Running: The thread is in running state if the thread


scheduler has selected it.

4) Non-Runnable (Blocked): This is the state when


the thread is still alive, but is currently not eligible to run.

5) Terminated: A thread is in terminated or dead state


when its run() method exits
CREATING A THREAD
In Java, an object of the Thread class can represent a thread. Thread can be implemented through any
one of two ways:
There are two ways to create a thread:

 By extending Thread class


 By implementing Runnable interface.
Extending the java.lang.Thread Class

For creating a thread a class have to extend the Thread Class. For creating a thread by
this procedure you have to follow these steps:

•Extend the java.lang.Thread Class.

•Override the run( ) method in the subclass from the Thread class to define the code
executed by the thread.

•Create an instance of this subclass. This subclass may call a Thread class constructor
by subclass constructor.

•Invoke the start( ) method on the instance of the class to make the thread eligible for
running.
Implementing the java.lang.Runnable Interface

The procedure for creating threads by implementing the Runnable Interface is as


follows:

•A Class implements the Runnable Interface, override the run() method to define the
code executed by thread. An object of this class is Runnable Object.

•Create an object of Thread Class by passing a Runnable object as argument.

•Invoke the start( ) method on the instance of the Thread class.


SYNCHRONIZATION IN JAVA

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
Thread 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. It
can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization
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 a 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 executed.It is implemented by following methods of
Object class:

o wait()
o notify()
o notifyAll()
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.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
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:
1. public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. public final void notifyAll()
JAVA ENUMS
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW,
BLUE, GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we should
have all constants in capital letters. So, we have enum constants in capital letters.

Java Enums can be thought of as classes which have a fixed set of constants (a variable that does
not change). The Java enum constants are static and final implicitly. It is available since JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java.
AUTOBOXING AND UNBOXING:
The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java
programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:


No need of conversion between primitives and Wrappers manually so less coding is required.
Thank
you

You might also like