Java 4 TH

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT-4

EXCEPTION HANDLING & MULTI-THREADING


EXCEPTION: (an abnormal condition)
An exception is unexpected/unwanted/abnormal situation that occurred at runtime called exception. An
exception is an event, which occurs during the execution of a program that disrupts the normal flow of the
program's instructions.
EXCEPTION HANDLING:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained.
SOURCES OF ERRORS:
There are different types of errors occurred during compilation and running a java program.
 Syntax errors
 Run time errors
 Logical errors
Syntax errors:
Errors that are detected by the compiler are called syntax errors compile errors. These errors are occurred by
missing semicolon, opening brace without corresponding closing brace, mistyping a keyword, omitting
some necessary punctuation.
Example:
public class Java Demo
public static void main
system.out.println(“Hello java”);
} }
Runtime errors:
The runtime errors are errors that cause a program to terminate abnormally. They occur while a program is
running if the environment detects an operation that is impossible to carry out. For example division by zero.
Example:
public class Java Demo
public static void main(
System.out.println(10/0);
} }
Output:
Exceptioninthread “main” java.lang.ArithmeticException: /byzero
Atcom.JavaDemo.main(JavaDemo.java:24)
Logical errors:
The logical errors are occurred when a program does not perform the way it was intended to. A logical error
in a program is an error were the instructions given in the program do not accomplish the intended goal.
Example:
public class JavaDemo
public static void main
System.out.println(“Celsius 35 is Fahrenheit degree”);
System.out.println((9/5) *35+32);
} }
Output:
Celsius35 is Fahrenheit degree
67
ADVANTAGES OF EXCEPTION HANDLING:
 Exception handling can control run time errors that occur in the program.
 It can avoid abnormal termination of the program and also shows the behavior of program to users.
 It can separate the error handling code and normal code by using try-catch block.
 A logical grouping of error types exceptions can be used to group together errors that are related.
 This separation results in less complex and more readable code.
 The ability to propagate errors up the call stack another important advantage of exception handling in
object oriented programming is the ability to propagate errors up the call stack.
TYPES OF EXCEPTIONS
In java we have 3 types of exceptions
 Checked exception.
 Un-checked exception.
 Errors.
Checked exception:
The exception that can be predicted by the programmer at the compile time. These type of exceptions must be
checked at compile time. These exceptions are extended from the java.lang.Exception class.
Example: File that needs to be opened is not found.
Un-checked exception:
An unchecked exception in Java is something that has gone wrong with the program and is unrecoverable.
Un-checked exceptions are the class that extends RuntimeException. Unchecked exceptions are ignored at
compile time. These exceptions are extended from java.lang.RunTimeException class. Those are checked at
runtime.
Example: Arithmetic Exception, Null Pointer Exception, Array Index Out of Bound Exception.
Error:
The term error means an action which is inaccurate or incorrect. Errors are typically ignored in code because
you can rarely do anything about an error.
Example:
If stack overflow occurs an error will rise. This type of error cannot be handled in the code.
Some exceptions may occur:
 Arithmetic Exception.
 Array index out of bounds exception
 IO exception
 File not found exception
 No such field exception.
UNDERSTANDING THE KEYWORDS TRY, CATCH, FINALLY, THROW AND THROWS
TRY: The try statement allows you to define a block of code to be tested for errors while it is being executed.
Try block is used to enclose the code that might throw an exception. It must be used within the method. Java
try block must be followed by either catch or finally block.
Syntax:
 Try-catch:
try {
//code that may throw exception
} catch (Exception_class_Name ref)
{
}
 Try-finally:
try {
//code that may throw exception
} finally
{
}
CATCH: Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. It must be used after the try block.
Example:
public class testtrycatch
{
public static void main(String[]args)
{
try{
int data=50/0;
}
Catch(ArithmeticException e){
System.out.println(e);
}
System.out.println(“rest of code…..”);
} }
FINALLY: The finally keyword is used to execute code no matter if there is an exception or not. Finally is a
block that is used to execute important code such as closing connection, stream.. etc. java finally block is
always executed whether exception is handled not. It will must followed by try or catch block.
Example:
class TestFinallyBlock
{
public static void main(String[]args)
{
try {
int data=25/5;
system.out.println(data);
}
catch(NullPointerException e) {
system.out.println(e);
}
finally {
system.out.println(“finally block is always executed”);
}
System.out.println(“rest of the code…”);
} }
THROW: The throw keyword is used to explicitly throw a single exception. We can throw checked or
unchecked exception in java by throw keyword. When an exception is thrown, the flow of program execution
transfers from the try block to the catch block. We use the throw keyword within a method. It is mainly used
to throw custom exception.
Example:
throw exception;
throw new IOException(“sorry device error”);
public class TestThrow
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[])
{
validate(13);
System.out.println(“rest of the code….”);
} }
THROWS: The throws keyword indicates what exception type may be thrown by a method. There are many
exception types are available in java:ArithmeticException, ClassNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException, etc. Syntax: throw is followed by an object.
Example:
public class Main
static void check Age (int age) throw Arithmetic Exception
if(age<18) {
throw new Arithmetic Exception(“Access denied-You must be at least 18 years old”);
}
else {
System.out.println(“Access granted-You are old enough!”);
} }
public static void main
checkedAge(15);
} }
DIFFERENCES BETWEEN THROW AND THROWS:

CONCEPT OF MULTI-CATCH STATEMENTS:


A try block can be followed by one or more catch blocks. Each catch block must contain a different exception
handler. In some cases, more than one exception could be raised by a single piece of code. To handle this type
of situation, you can specify two more catch statement is inspected in order, and the first one whose type
matches that of the exception is executed. After one catch statement executes, the others are bypassed, and
execution continues after the try/catch block.
Syntax:
try {
stmts
}
catch(Exceptiontype 1e)
{
statement;
}
.
.
catch(Exceptiontype n e)
{
statements;
}
Example:
class Multi catch Statement
{
public static void main
{
int arr []={5,10};
int b=5;
try {
int x=arr[2]/(arr[0]-b);
}
catch(ArithmeticException ae)
{
System.out.println(“divide by zero not possible”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“can not possible to access an element out of Array bounds”);
}
catch(ArrayStoreException e)
{
System.out.println(“can not store different type of values”);
}
finally
{
int y=a[1]/a[0];
System.out.println(“y=”+y);
} } }
NESTED TRY IN EXCEPTION HANDLING
The try statement can be nested. A try statement can be inside the block of another try.In Java, we can use a
try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to
a stack. Given below is an example of a nested try. Sometimes a situation may arise where a part of a block
may cause one error and the entire block itself may cause another error.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 3;
statement 4;
}
catch(Exception e2)
{
}
}
catch(Exception e1)
{
}
Example:
class NestedtryExcep
{
public static void main()
{
try
{
int arr[]={1,0,4,2};
try{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println(“divide by zero not possible”);
}
arr[4]=3;
}
catch(ArrayIndexOutOfBondException e)
{
System.out,println(“Array index out of bounds exception”);
}}}
BUILT IN EXCEPTIONS
Runtime exceptions are represented in the RuntimeException class, which describes programming errors, such
as bad casting, accessing an out-of-bounds array, and numeric errors. Runtime exceptions are generally thrown
by the JVM.
Types of build-in exceptions:
 Arithmetic exception: It is thrown when an exceptional condition has occurred in an arithmetic
operation.
 ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
 ClassNotFoundException: This Exception is raised when we try to access a class whose definition is
not found.
 FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
 IOException: It is thrown when an input-output operation failed or interrupted.
 NullPointerException: This exception is raised when referring to the members of a null object. Null
represents nothing.
MULTI THREADING
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. A multi-threaded program contains two or more parts that can run concurrently. A process
consists of the memory space allocated by the operating system that can contain one more threads. A thread
cannot exist on its own it must be a part of a process.
Benefits of multi-threading:
1. Enables programmers to do multiple things at one time.
2. Programmers can divide a long program into threads and execute them in parallel which eventually
increases the speed of the program execution.
3. Improved performance and concurrency.
4. Simultaneous access to multiple applications.
THREAD LIFE CYCLE AND STATES
A thread can be in one of the five states.
1. New
2. Runnable
3. Running
4. Blocked
5. Dead.
New: Whenever a new thread is created, it is always in the new state. New thread is created and said to be
new born stage. From this stage thread will be entered in to next state by using start() method.
Runnable: After creating new thread the task will be assigned so the thread is ready to execute and waiting
for the availability of the processor.
Running: In this stage the processor has given its time to the thread for execution it will be keep running.
*** The thread will be going from running state to runnable state and return from runnable state to running
state by using yield() method.
From this stages we can terminate or dead the thread by using stop() method. And we can block the thread for
some duration of time by using suspend() if can use this method and we want to restart the thread by using
resume() method. sleep(t) method can be used for keep thread in idle. We have another method for waiting
the thread for going to execute is wait(). This method will wait for certain time and will be return to job
sequence by using notify() method. this method will indicates getting ready for the execution.
Block: If a thread is prevented from entering into runnable state and subsequently running state, then a thread
is said to be in blocked state.
Dead: A runnable thread enters to the dead or terminated state when it completes its task. In some cases we
are terminated the thread from the states of new born, running and blocked by using stop() method.
CREATING SINGLE THREAD
We can create thread in two ways
 Implement the runnable interface
 Extend the thread class
Creating thread by implementing runnable:
The easiest way to create a thread is to create a class that implements the runnable interface. To implement
runnable a class need only implement a sinhle mrthod called run().
public void run()
after the new thread is created it will not start running until you call its start() method, which is declared
within the thread.
void start();
Example:
public class ExampleClass implements Runnable {
public void run() {
System.out.println("Thread has ended");
}
public static void main(String[] args) {
ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}
Creating thread by extending thread class:
The second way to create a thread is to create a new class that extends thread and then to create an instance of
that class. The extending class must override the run() method, which is an entry point. It must also call start()
to begin execution of the new thread.
Example:
import java.io.*;
class GFG extends Thread {
public void run()
{
System.out.print("Welcome to GeeksforGeeks.");
}
public static void main(String[] args)
{
GFG g = new GFG(); // creating thread
g.start(); // starting thread
}
}
Thread methods

S.N. Modifier and Method Description


Type

1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread
object.

5) void join() It waits for a thread to die

CRETING MULTI-THREAD
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in
the Thread class. A thread begins its life inside run() method. We create an object of our new class and call
start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Example:
class MultithreadingDemo extends Thread {
public void run()
{
try {
System.out.println(
"Thread " + Thread.currentThread().getId() + " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing runnable interface:
The Runnable interface describes a class whose instances can be run as a thread. The interface itself is very
simple, describing only one method (run) that is called automatically by Java when the thread is started.
Example:
class MultithreadingDemo implements Runnable {
public void run()
{
try {
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
THREAD PRIARITIES IN MULTIPLE THREADS
Every java thread has a priority that helps the operating system determine the order in which threads are
scheduled. Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads.
Java Thread Priority in Multithreading
MAX_PRIORITY − The maximum priority that a thread has, whose default value is 10.
NORM_PRIORITY − The default priority that a thread has, whose default value is 5.
MIN_PRIORITY − The minimum priority that a thread has, whose default value is 1.
Use of isAlive() and join() methods in thread priority.
 isAlive(): The isAlive function − It is used to check if a thread is alive or not. Alive refers to a thread
that has begun but not been terminated yet. When the run method is called, the thread operates for a
specific period of time after which it stops executing.
Syntax: final Boolean isAlive()
 join(): Join method in Java allows one thread to wait until another thread completes its execution. In
simpler words, it means it waits for the other thread to die. It has a void type and throws
InterruptedException.
Syntax: public final void join() throws InterruptedException
Example:
import java.lang.*;
public class Demo implements Runnable {
public void run() {
Thread t = Thread.currentThread(); // tests if this thread is alive
System.out.println("thread is live = " + t.isAlive()); // tests if this thread is alive
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new Demo());
t.start(); // this will call run() function
t.join(); // waits for this thread to die
System.out.println("thread is live = " + t.isAlive()); // tests if this thread is alive
}
}
Output:
thread is live = true
thread is live = false
CONCEPT OF SYNCHRONIZATION
The synchronization is a capability to control the access of multiple threads to any shared resource. The
process by which this synchronization is called thread synchronization. Every java object with a critical section
of code gets a lock associated with the object.
Syntax:
synchronized (object)
{
//statement to be sychronized
}
The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.
Types of Synchronization
 Process Synchronization
 Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
 Synchronized method.
 Synchronized block.
 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:
 By Using Synchronized Method
 By Using Synchronized Block
 By Using Static Synchronization
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or monitor. Every object has a 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.
Synchronized block in java
A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource
of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a
synchronized block is smaller than the synchronized method.
Problem with using synchronization
The JVM uses the object itself as a monitor when a class implements method synchronization or block
synchronization with the This keyword. Untrusted code can obtain and indefinitely hold the inbuilt lock of an
accessible class. Consequently, this can result in a deadlock situation.
Example:
synchronized void updatesum (int i)
{
Thread t = Thread.currentThread();
for(int n=1; n<=5; n++)
{
System.out.println(t.getName()+ “;”+(i+n));
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} }
INTER THREAD COMMUNICATION
Inter-thread communication or co-operation is all about allowing synchronized threads are to be
communicated 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.
 wait()
 notify()
 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.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException 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: public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()
Understanding the process of inter-thread communication

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 wait() method on the object. Otherwise it releases the lock
and exits.
4. If you call notify() 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:
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}c.start();
new Thread(){
public void run(){c.deposit(10000);}
}c.start();
}}
DEADLOCK
Deadlock in java is a part of multithreading. The deadlock is situation when a thread is waiting for an object
lock, that is acquired by another thread and second thread is waiting for an object lock is acquired by first
thread. Hence both threads are waiting for each other to release the lock, the condition is called deadlock.

Example:
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}

You might also like