Unit - III Java
Unit - III Java
Unit –III
Exception Handling: try – catch - throw - throws –- finally – Built-in exceptions - Creating
own Exception classes - garbage collection, finalise -Multithreaded Programming: Thread Class
- Runnable interface – Synchronization – Using synchronized methods – Using synchronized
statement - Interthread Communication – Deadlock.
Exception Handling:
1. ClassNotFoundException,
2. IOException,
3. SQLException,
4. RemoteException, etc.
An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
1
Unit - III[Type here] Java Programming II BCA
Checked Exception
Unchecked Exception
Error
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.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.
JavaExceptionExample.java
2
Unit - III[Type here] Java Programming II BCA
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Built in Exceptions:
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in exceptions
in Java.
Output:
3
Unit - III[Type here] Java Programming II BCA
ArrayIndexOutOfBoundsException :
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.
Java program to demonstrate.
FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[])
{
try {
// Following file does not exist
File file = new File("E:// file.txt");
FileReaderfr = new FileReader(file);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:
Array Index is Out Of Bounds
} class Geeks {
} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}
Output:
ClassNotFoundException
FileNotFoundException : This Exception is raised when a file is not accessible or does not
open.
4
Unit - III[Type here] Java Programming II BCA
Output:
File does not exist
IOException : It is thrown when an input-output operation failed or interrupted
JAVA
Output:
error: unreported exception IOException; must be caught or declared to be thrown
InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
error: unreported exception InterruptedException; must be caught or declared to be thrown
NoSuchMethodException : t is thrown when accessing a method which is not found.
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
NullPointerException : This exception is raised when referring to the members of a null
object. Null represents nothing .
JAVA
5
Unit - III[Type here] Java Programming II BCA
System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
NullPointerException..
NumberFormatException : This exception is raised when a method could not convert a string
into a numeric format.
Output:
StringIndexOutOfBoundsException
An exception is an issue (run time error) that occurred during the execution of a
program.
When an exception occurred the program gets terminated abruptly and, the code
past the line that generated the exception never gets executed.
In order to create a custom exception, we need to extend the Exception class that belongs
to java.lang package.
6
Unit - III[Type here] Java Programming II BCA
public MyException(String s)
super(s);
// Driver Program
try {
System.out.println("Caught");
7
Unit - III[Type here] Java Programming II BCA
System.out.println(ex.getMessage());
Output
Caught
GeeksGeeks
Java Garbage Collection
In java, garbage means unreferenced objects.
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
8
Unit - III[Type here] Java Programming II BCA
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight processes within
a process.
Threads can be created by using two mechanisms :
Extending the Thread class
Implementing the Runnable Interface
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.
Java
9
Unit - III[Type here] Java Programming II BCA
classMultithreadingDemo extendsThread {
publicvoidrun()
try{
System.out.println(
+ " is running");
catch(Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
publicclassMultithread {
publicstaticvoidmain(String[] args)
10
Unit - III[Type here] Java Programming II BCA
MultithreadingDemo object
= newMultithreadingDemo();
object.start();
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
11
Unit - III[Type here] Java Programming II BCA
try{
// Displaying the thread that is running
System.out.println(
"Thread "+ Thread.currentThread().getId()
+ " is running");
}
catch(Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
classMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
Thread object
= newThread(newMultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
If we extend the Thread class, our class cannot extend any other class because Java
doesn’t support multiple inheritance.
But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it
provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.
Using runnable will give you an object that can be shared amongst multiple threads.
12
Unit - III[Type here] Java Programming II BCA
Synchronization in Java
Multi-threaded programs may often come to a situation where multiple threads try to
access the same resources and finally produce erroneous and unforeseen results.
Types of Synchronization
There are two synchronizations in Java mentioned below:
Process Synchronization
Thread Synchronization
Types of Synchronization
There are two synchronizations in Java mentioned below:
Process Synchronization
Thread Synchronization
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. There are three types of Mutual Exclusive mentioned below:
Synchronized method.
Synchronized block.
Static synchronization.
Example of Synchronization
import java.io.*;
import java.util.*;
13
Unit - III[Type here] Java Programming II BCA
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
Output
Sending Hi
14
Unit - III[Type here] Java Programming II BCA
Hi Sent
Sending Bye
Bye Sent
1. wait()
2. notify()
3. notifyAll()
4. 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(long 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:
3) notifyAll() method
15
Unit - III[Type here] Java Programming II BCA
Syntax:
After completion of the task, thread releases the lock and exits the monitor state of the object.
Test.java
class Customer{
int amount=10000;
16
Unit - III[Type here] Java Programming II BCA
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...");
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
17
Unit - III[Type here] Java Programming II BCA
Deadlock in Java
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
18
Unit - III[Type here] Java Programming II BCA
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:
Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason for
a deadlock condition. It normally happens when you give locks to multiple threads.
Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to
the unnecessary threads that cause the deadlock condition.
Using Thread Join: A deadlock usually happens when one thread is waiting for the other to
finish. In this case, we can use join with a maximum time that a thread will take.
19