0% found this document useful (0 votes)
2 views28 pages

Java Programming Module-3

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Java Programming Module-3

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BCA PROGRAM

nd
SEM-2

JAVA PROGRAMMING
Module 3
Exception Handling: Exception types, uncaught
exceptions, multiple catch clauses, built-in exceptions,
creating your own exceptions.
Multi-Threading: Multithreading and String Handling:
Multithreading: Java thread model, creating multiple
threads, thread priorities, synchronization, inter-thread
communication, suspending, resuming and stopping
threads.
EXCEPTIONS
Exceptions in Java
Exception Handling in Java is one of the effective means to handle runtime errors
so that the regular flow of the application can be preserved. Java Exception
Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as the
name and description of the exception and the state of the program when the
exception occurred.
Exceptions
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of the
programmer, and we should not try to handle errors.
Types of Exception in Java with Examples
.

Java defines several types of Built-in Exceptions:


exceptions that relate to its Built-in exceptions are the exceptions that are available in
Java libraries. These exceptions are suitable to explain
various class libraries. Java certain error situations. Below is the list of important
also allows users to define built-in exceptions in Java.
[Link]: It is thrown when an exceptional
their own exceptions. condition has occurred in an arithmetic operation.
[Link]: 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.
[Link] : This Exception is raised
when we try to pass string.
[Link]: This Exception is raised when a
file is not accessible or does not open.
[Link] : It is thrown when an NULL is
assigned to a variable.
// Java program to demonstrate ArithmeticException
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
//Java program to demonstrate
{ //NullPointerException
try class NullPointer_Demo
{ {
int a = 30, b = 0; public static void main(String args[])
int c = a/b; // cannot divide by zero {
[Link] ("Result = " + c); try {
} String a = null; //null value
catch(ArithmeticException e) [Link]([Link](0));
} catch(NullPointerException e) {
{
[Link] ("Can't divide a number [Link]("NullPointerException..");
by 0"); }
} }
} }
}
// Java program to demonstrate Exception
//Java program to demonstrate try
//FileNotFoundException {
// Following file does not exist
import [Link]; File file = new File("E://[Link]");
FileReader fr = new FileReader(file);
import [Link];
}
import [Link]; catch (FileNotFoundException e)
class File_notFound_Demo {
{ [Link]("File does not exist");
public static void main(String args[]) }
{ try
{
// Harry is not a number
int num = [Link] ("Harry") ;
[Link](num);
}
catch(NumberFormatException e)
{
[Link]("Number format
exception");
}
// Java program to demonstrate Exception
try
{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link] ("Array Index is Out Of Bounds");
}
}
}
Creating User-Defined Exceptions
1. Decide on the Exception Type
Determine whether your exception should be checked or unchecked. This
depends on how you want the exception to be handled. If it's a recoverable
condition and you want to enforce its handling, make it a checked exception. If
it's for a programming error or an unrecoverable condition, make it unchecked.
2. Define a New Exception Class
Create a new class that extends either Exception (for a checked exception)
or RuntimeException (for an unchecked exception).
3. Add Constructors
Your exception class should include constructors. At a minimum, you should
provide a default constructor and a constructor that takes a String message as a
parameter.
What are User-Defined Exceptions?

User-defined exceptions are custom exceptions that a


programmer can add to their code to deal with specific error
conditions or situations.
These exceptions are derived from the base exception class
and allow the programmer to customize the
exception-handling process to meet their specific
requirements.
User-defined exceptions are used to indicate errors that are
specific to the application being developed, and they are
frequently used in code to provide a higher level of
abstraction and readability.
How to Implement User-defined Exception in Java?
Steps to Create a User-Defined Exception
Create a class that extends Exception
Define a constructor to accept an error message.
Use throw to raise the exception where appropriate.
Catch and handle the exception using try-catch.
Example program on user defined exceptions
class InvalidAgeException extends Exception {
public static void main(String[] args) {
public InvalidAgeException(String message) { try {
super(message); validateAge(15);
} catch (InvalidAgeException e) {
} [Link]("Caught Exception: " +
} [Link]());
}
public class Main { }
}
static void validateAge(int age) throws
}
InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must
be 18 or above.");
}
[Link]("Valid age. Access
granted.");
}
// Example program on a custom exception
class NegativeAmountException extends RuntimeException {
public NegativeAmountException(String message) {
super(message);
}
}
public class BankTransaction {
static void deposit(int amount) {
if (amount < 0) {
throw new NegativeAmountException("Amount cannot be negative.");
}
[Link]("Deposited: " + amount);
}
public static void main(String[] args) {
deposit(-100); // Throws unchecked exception
}
}
Java Multi-catch block
A try block can be followed by one or public class MultipleCatchBlock1 {

more catch blocks. Each catch block public static void main(String[] args) {
must contain a different exception try{
handler. So, if you have to perform int a[]=new int[5];
a[5]=30/0;
different tasks at the occurrence of }
different exceptions, use java catchArithmeticException e)
{
multi-catch block. [Link]("Arithmetic Exception occurs");
}
At a time only one exception occurs catchArrayIndexOutOfBoundsException e)
{
and at a time only one catch block is [Link]("ArrayIndexOutOfBounds Exception occurs");
executed.
}
All catch blocks must be ordered catchException e)
{
from most specific to most general, [Link]("Parent Exception occurs");
}
i.e. catch for ArithmeticException [Link]("rest of the code");
must come before catch for }
}
Exception.
What is Multithreading?
15
Multithreading is a programming concept in which the
application can create a small unit of tasks to execute in
parallel.
Threads allow us to do things more quickly in Java. That
is, they help us perform multiple things all at once.
You use threads to perform complex operations without
any disturbance in the main program.
When various multiple threads are executed at the same
time, this process is known as multi-threading.
Multi-threading is mainly used in gaming and similar
programs. Since we now know a bit about multi-threading,
JAIN UNIVERSITY BCA
let's also learn about the concept of multi-tasking..
How does Java Support Multithreading?
Java has great support for multithreaded applications. Java supports
multithreading through Thread class.
Java Thread allows us to create a lightweight process that executes some tasks.
We can create multiple threads in our program and start them.
Java runtime will take care of creating machine-level instructions and work
with OS to execute them in parallel.
What is Thread Priority?
When we create a thread, we can assign its priority. We can set different
priorities to different Threads but it doesn’t guarantee that a higher priority
thread will execute first than a lower priority thread. The thread scheduler is
the part of Operating System implementation and when a Thread is started, its
execution is controlled by Thread Scheduler and JVM doesn’t have any control
over its execution.
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states.
A thread lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
Thread Life Cycle
New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run
when the thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t
started to execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might
actually be running or it might be ready to run at any instant of time. It is the responsibility of the thread
scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every
thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other
threads can get a chance to run. When this happens, all such threads that are ready to run, waiting for the
CPU and the currently running thread lie in a runnable state.
Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is
acquired by the other thread. The thread will move from the blocked state to runnable state when it
acquires the lock.
Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter.
A thread lies in this state until the timeout is completed or until a notification is received. For example,
when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed by the program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception.
Advantage of Multithreading in Java
The advantages of using multithreading programming concept are as follows:
1. In a multithreaded application program, different parts of the application are executed by different
threads. The entire application does not stop even if an exception occurs in any of the threads. It does
not affect other threads during the execution of the application.
2. Different threads are allotted to different processors and each thread is executed in different
processors in parallel.
3. Multithreading helps to reduce computation time.
4. Multithreading technique improves the performance of the application.
5. Threads share the same memory address space. Hence, it saves memory.
6. Multithreaded program makes maximum utilization of CPU and keeping the idle time of CPU to
minimum.
7. Context switching from one thread to another thread is less expensive than between processes.
Drawbacks of Multithreading in Java

The drawbacks of multithreading are as follows:


1. Increased complexity.
2. Synchronization of shared resources.
3. In the multithreading programming concept, debugging is difficult.
At times, result is unpredictable.
4. Potential deadlocks.
5. Programming complications may occur.
Thread Class and Methods in Java
In Java, Thread class contains several
constructors for creating threads for tasks and
methods for controlling threads. It is a
predefined class declared in [Link] default
package.
Each thread in Java is created and controlled by
a unique object of the Thread class. An object
of thread controls a thread running under JVM.
Thread class contains various methods that can
be used to start, control, interrupt the execution
of a thread, and for many other thread related
activities in a program.
Thread class extends Object class and it
implements Runnable interface. The
declaration of thread class is as follows:
public class Thread
extends Object
implements Runnable
Methods of Thread Class in Java
Thread methods in Java are very important while you're working with a multi-threaded
application.
public void start(): you use this method to start the thread in a separate path of execution. Then
it invokes the run() method on the thread object.
public void run(): this method is the starting point of the thread. The execution of the thread
begins from this process.
public final void setName(): this method changes the name of the thread object. There is also a
getName() method for retrieving the name of the current context.
public final void setPriority(): you use this method to set the values of the thread object.
public void sleep(): you use this method to suspend the thread for a particular amount of time.
public void interrupt(): you use this method to interrupt a particular thread. It also causes it to
continue execution if it was blocked for any reason.
public final boolean isAlive(): this method returns true if the thread is alive.
How to Create a Thread in Java
There are two ways to create a thread:
First, you can create a thread using the thread class (extend syntax).
This provides you with constructors and methods for creating and
operating on threads.
The thread class extends the object class and implements a runnable
interface. The thread class in Java is the main class on which Java’s
multithreading system is based.
Second, you can create a thread using a runnable interface. You can use
this method when you know that the class with the instance is intended
to be executed by the thread itself.
The runnable interface is an interface in Java which is used to execute
concurrent thread. The runnable interface has only one method which is
run().
How to Create a Thread in Java
//Write a program that creates 3 threads
class A extends Thread
class C extends Thread
{
public void run()
{
{ public void run()
for(int i=1;i<=5;i++) {
{ for(int k=1;k<=5;k++)
[Link]("\t From ThreadA: i= "+i); {
} [Link]("\t From ThreadC: k= "+k);
[Link]("Exit from A"); }
}
[Link]("Exit from C");
}
class B extends Thread
}
{ }
public void run() class ThreadTest
{ {
for(int j=1;j<=5;j++) public static void main(String args[])
{ {
[Link]("\t From ThreadB: j= "+j); new A().start();
}
new B().start();
[Link]("Exit from B");
}
new C().start();
} }
}
Thread Priority
„ In Java, each thread is assigned priority, which Thread Priority Example
class A extends Thread
affects the order in which it is scheduled for {
running. The threads so far had same default public void run()
{
priority (NORM_PRIORITY) and they are [Link]("Thread A started");
served for(int i=1;i<=4;i++)
{
using FCFS policy. [Link]("\t From ThreadA: i= "+i);
„ Java allows users to change priority: }
[Link]("Exit from A");
„ [Link](intNumber) }
„ MIN_PRIORITY = 1 }
class B extends Thread
„ NORM_PRIORITY=5 {
„ MAX_PRIORITY=10 public void run()
{
[Link]("Thread B started");
for(int j=1;j<=4;j++)
{
[Link]("\t From ThreadB: j= "+j);
}
[Link]("Exit from B");
}
}
Thread Priority
class C extends Thread class ThreadPriority
{ {
public void run() public static void main(String args[])
{
{
A threadA=new A();
[Link]("Thread C started");
B threadB=new B();
for(int k=1;k<=4;k++) C threadC=new C();
{ [Link](Thread.MAX_PRIORITY);
[Link]("\t From ThreadC: k= "+k); [Link]([Link]()+1);
} [Link](Thread.MIN_PRIORITY);
[Link]("Exit from C"); [Link]("Started Thread A");
} [Link]();
} [Link]("Started Thread B");
[Link]();
[Link]("Started Thread C");
[Link]();
[Link]("End of main thread");
}
}
Suspending, resuming, and stopping threads in Java
suspendThread(): This method temporarily halts the execution of the thread. It is
not recommended for use in modern Java as it can lead to deadlocks and other
concurrency issues.
resumeThread(): This method resumes a suspended thread. It should only be called
after the thread has been suspended with suspend().
stopThread(): This method terminates a thread. It is deprecated due to the risk of
inconsistent state or resources not being released [Link] Threads in
Java
In Java, a thread can be suspended by using the wait() method on an object. This
method suspends thread execution until it is notified by another thread using the
notify() method. As an example:
public class ThreadControlExample {
public static void main(String[] args) throws
InterruptedException {
class MyThread extends Thread { MyThread thread = new MyThread();

public void run() { // Start the thread


try { [Link]();

int count = 0; // Allow the thread to run for 3 seconds


[Link](3000);
while (count < 10) {
[Link]("Count: " + count); // Suspend the thread
[Link]("Suspending thread...");
count++; [Link](); // Deprecated method
[Link](1000); // Simulate some work
// Allow the thread to remain suspended for 2 seconds
} [Link](2000);
} catch (InterruptedException e) {
// Resume the thread
[Link]("Thread interrupted"); [Link]("Resuming thread...");
[Link](); // Deprecated method
}
} // Allow the thread to run for another 3 seconds
[Link](3000);
}
// Stop the thread
[Link]("Stopping thread...");
[Link](); // Deprecated method
}
}

You might also like