Unit 3
Unit 3
1. Exception in Java
An exception is an unexpected event that occurs during program execution.
It affects the flow of the program instructions which can cause the program to
terminate abnormally.
It is an object which is thrown at runtime.
1. Built-in Exceptions
1. Checked Exceptions
2. Unchecked Exceptions
2. User-Defined Exceptions / Custom Exceptions
1. Built-in Exceptions
There are 2 types.
1. Checked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn't handle or declare
it, the program would not give a compilation error. Usually, it occurs when the
user provides bad data during the interaction with the program.
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.
Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e. Exception
class that can be obtained using getMessage() method on the object we have
created.
Java provides five keywords that are used to handle the exception.
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block
must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
try {
catch(Exception e) {
class Example1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:
You Shouldn't divide a number by zero
Explanation: In the above example I’ve divided an integer by a zero and
because of this ArithmeticException is thrown.
Output:
ArrayIndexOutOfBounds
In the above example the array is initialized to store only 10 elements indexes 0
to 9. Since we are try to access element of index 11, the program is throwing
this exception.
E.g.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
13
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the String.
Output:
NullPointerException.
2. finally block
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
4. throw keyword
In Java, an exception allows us to write good quality codes where the errors are
checked at the compile time instead of runtime.
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description.
Output:
Welcome to the Registration process!!Exception in thread "main"
5. throws keyword
So, it is better for the programmer to provide the exception handling code so
that the normal flow of the program can be maintained.
//method code
Output:
java.io.IOException: IOException Occurred
3. User-Defined Exceptions / Custom Exceptions / Creating own
exception subclasses
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.
Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e. Exception
class that can be obtained using getMessage() method on the object we have
created.
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
It's execution is
not dependant on
the exception.
7. Multithreading
Thread
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
8. Multiprocessing Vs Multithreading
While In Multithreading,
many threads are created of
In Multiprocessing, CPUs are added
1. a single process for
for increasing computing power.
increasing computing
power.
While in multithreading,
In Multiprocessing, Many processes
2. many threads of a process
are executed simultaneously.
are executed simultaneously.
While in Multithreading,
In Multiprocessing, Process creation
4. process creation is according
is a time-consuming process.
to economical.
5. While in Multithreading, a
In Multiprocessing, every process
common address space is
S.No. Multiprocessing Multithreading
1. NEW – a newly created thread that has not yet started the execution.
2. RUNNABLE – either running or ready for execution but it's waiting for
resource allocation.
3. BLOCKED – waiting to acquire a monitor lock to enter or re-enter a
synchronized block/method.
4. WAITING – waiting for some other thread to perform a particular action
without any time limit.
5. TIMED_WAITING – waiting for some other thread to perform a specific
action for a specified period.
6. TERMINATED – has completed its execution.
10. Creating threads:
The java programming language provides two methods to create threads, and
they are listed below.
To create a thread using Thread class, follow the steps given below.
Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the
thread. The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
Output:
Thread is running
The java contains a built-in interface Runnable inside the java.lang package.
The Runnable interface implemented by the Thread class that contains all the
methods that are related to the threads.
To create a thread using Runnable interface, follow the steps given below.
Step-2: Override the run( ) method with the code that is to be executed by the
thread. The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as
parameter to the Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above
step.
Output:
Thread is running
11. Commonly used methods of Thread class
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number of
milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10.public Thread currentThread(): returns the reference of currently
executing thread.
11.public int getId(): returns the id of the thread.
12.public Thread.State getState(): returns the state of the thread.
13.public boolean isAlive(): tests if the thread is alive.
14.public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15.public void suspend(): is used to suspend the thread(depricated).
16.public void resume(): is used to resume the suspended thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public boolean isDaemon(): tests if the thread is a daemon thread.
19.public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20.public void interrupt(): interrupts the thread.
21.public boolean isInterrupted(): tests if the thread has been interrupted.
22.public static boolean interrupted(): tests if the current thread has been
interrupted.
If the thread is not in the sleeping or waiting state, calling the interrupt() method
performs normal behaviour and doesn't interrupt the thread but sets the interrupt
flag to true.
In this example, after interrupting the thread, we are propagating it, so it will
stop working. If we don't want to stop the thread, we can handle it where sleep()
or wait() method is invoked. Let's first see the example where we are
propagating the exception.
}
}
Output:
Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
The Thread class also contains three constants that are used to set the thread
priority, and they are listed below.
import java.lang.*;
// Method 1
// 1st Thread
// 2nd Thread
// 3rd Thread
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
// 3
// 9
// Main thread
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
1. Process Synchronization
1. wait()
2. notify()
3. 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:
public final void notify()
3) notifyAll() method
Syntax:
Producer and Consumer are two separate processes. Both processes share a
common buffer or queue. The producer continuously produces certain data and
pushes it onto the buffer, whereas the consumer consumes those data from the
buffer.
Both producer and consumer may try to update the queue at the same
time. This could lead to data loss or inconsistencies.
Producers might be slower than consumers. In such cases, the consumer
would process elements fast and wait.
In some cases, the consumer can be slower than a producer. This situation
leads to a queue overflow issue.
Problem
To make sure that the producer won’t try to add data into the buffer if
it’s full and that the consumer won’t try to remove data from an empty
buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it notifies
the producer, who starts to fill the buffer again. In the same way, the
consumer can go to sleep if it finds the buffer to be empty. The next
time the producer puts data into the buffer, it wakes up the sleeping
consumer.
An inadequate solution could result in a deadlock where both processes
are waiting to be awakened.
Example Program
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
// t1 finishes before t2
t1.join();
t2.join();
}
System.out.println("Producer produced-"
+ value);
System.out.println("Consumer consumed-"
+ val);
// and sleep
Thread.sleep(1000);
}
}
}
}
}
Output:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2