0% found this document useful (0 votes)
27 views

Unit - III Java

Unit III of the Java Programming course covers Exception Handling, including built-in exceptions and creating custom exceptions, as well as Garbage Collection and Multithreaded Programming. It explains the mechanisms for handling runtime errors, the importance of maintaining application flow, and the use of threads for concurrent execution. Additionally, it discusses synchronization techniques to prevent thread interference and ensure safe resource access.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Unit - III Java

Unit III of the Java Programming course covers Exception Handling, including built-in exceptions and creating custom exceptions, as well as Garbage Collection and Multithreaded Programming. It explains the mechanisms for handling runtime errors, the importance of maintaining application flow, and the use of threads for concurrent execution. Additionally, it discusses synchronization techniques to prevent thread interference and ensure safe resource access.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Unit - III[Type here] Java Programming II BCA

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:

 The Exception Handling in Java is powerful mechanisms to handle the runtime


errors so that the normal flow of the application can be maintained.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as

1. ClassNotFoundException,
2. IOException,
3. SQLException,
4. RemoteException, etc.

Advantage of Exception Handling

 Maintain the normal flow of the application.

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;

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked.

An error is considered as the unchecked exception.

1
Unit - III[Type here] Java Programming II BCA

 Checked Exception
 Unchecked Exception
 Error

Java Exception Keywords

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.

throw The "throw" keyword is used to throw an exception.

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.

Java Exception Handling Example

JavaExceptionExample.java

public class JavaExceptionExample{

2
Unit - III[Type here] Java Programming II BCA

public static void main(String args[]){


try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

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.

Arithmetic exception: It is thrown when an exceptional condition has occurred in an arithmetic


operation.

// Java program to demonstrate


// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}

Output:

3
Unit - III[Type here] Java Programming II BCA

Can't divide a number by 0

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

ClassNotFoundException : This Exception is raised when we try to access a class whose


definition is not found.

// Java program to illustrate the


// concept of ClassNotFoundException
class Bishal {

} 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

// 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:
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

// Java program to demonstrate


// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element

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.

StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an


index is either negative than the size of the string.
JAVA

// Java Program to illustrate


// StackOverflowError
class Test {
public static void main(String[] args)
{
m1();
}
public static void m1()
{
m2();
}
public static void m2()
{
m1();
}
}

Output:
StringIndexOutOfBoundsException

CREATING OUR OWN EXCEPTION:

 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

// A Class that represents use-defined exception

class MyException extends Exception {

public MyException(String s)

// Call constructor of parent Exception

super(s);

// A Class that uses above MyException

public class Main {

// Driver Program

public static void main(String args[])

try {

// Throw an object of user defined exception

throw new MyException("GeeksGeeks");

catch (MyException ex) {

System.out.println("Caught");

// Print the message from MyException object

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.

 Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


 It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

1)By nulling a reference:


Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

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

protected void finalize(){}

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.

public static void gc(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected

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

// Java code for thread creation by extending

9
Unit - III[Type here] Java Programming II BCA

// the Thread class

classMultithreadingDemo extendsThread {

publicvoidrun()

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

publicclassMultithread {

publicstaticvoidmain(String[] args)

10
Unit - III[Type here] Java Programming II BCA

intn = 8; // Number of threads

for(inti = 0; i< n; i++) {

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

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.

Java code for thread creation by implementing


the Runnable Interface
classMultithreadingDemo implementsRunnable {
publicvoidrun()
{

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

Process Synchronization in Java

 Process Synchronization is a technique used to coordinate the execution of multiple


processes. It ensures that the shared resources are safe and in order.

Thread Synchronization in Java

 Thread Synchronization is used to coordinate and ordering of the execution of the


threads in a multi-threaded program. There are two types of thread synchronization are
mentioned below:
 Mutual Exclusive
 Cooperation (Inter-thread communication in Java)

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.*;

// A Class used to send a message


class Sender {
public void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}

13
Unit - III[Type here] Java Programming II BCA

System.out.println("\n" + msg + "Sent");


}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
sender.send(msg);
}
}
}

// 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);

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}

Output
Sending Hi

14
Unit - III[Type here] Java Programming II BCA

Hi Sent
Sending Bye

Bye Sent

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:

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()throws InterruptedException It waits until object is notified.

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:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

15
Unit - III[Type here] Java Programming II BCA

Syntax:

public final void notifyAll()

 The point to point explanation of the above diagram is as follows:


 Threads enter to acquire lock.
 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
 If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
 Now thread is available to acquire lock.

After completion of the task, thread releases the lock and exits the monitor state of the object.

Example of Inter Thread Communication in Java

Test.java

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");

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...");
}

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);}
}.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

 Deadlock in Java is a part of multithreading. Deadlock can occur in a 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 that is acquired by first thread.
 Since, both threads
hreads are waiting for each other to release the lock, the condition is called
deadlock.

public class TestDeadlockExample1 {


public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
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");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

18
Unit - III[Type here] Java Programming II BCA

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};

t1.start();
t2.start();
}
}

Output:

Thread 1: locked resource 1


Thread 2: locked resource 2

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.

(Unit – III completed)

19

You might also like