0% found this document useful (0 votes)
72 views21 pages

Wawtg 20240327-053234

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)
72 views21 pages

Wawtg 20240327-053234

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
You are on page 1/ 21

Unit 4 : Exception Handling And Multithreading

Error:
• Error is an illegal operation performed by the user which results in the abnormal working
of the program.
• Programming errors often remain undetected until the program is compiled or executed.
• Some of the errors inhibit the program from getting compiled or executed.
• Thus errors should be removed before compiling and executing.

Types Of Errors:
1. Run time error
2. Compile time error

1.Run time error

➢ Run Time errors occur or we can say, are detected during the execution of the program.
➢ Sometimes these are discovered when the user enters an invalid data or data which is not
relevant.
➢ Runtime errors occur when a program does not contain any syntax errors but asks the
computer to do something that the computer is unable to reliably do.
➢ During compilation, the compiler has no technique to detect these kinds of errors.
➢ It is the JVM (Java Virtual Machine) that detects it while the program is running.
➢ To handle the error during the run time we can put our error code inside the try block and
catch the error inside the catch block.

2.Compile time error:

➢ Compile Time Errors are those errors which prevent the code from running because of
an incorrect syntax such as a missing semicolon at the end of a statement or a missing
bracket, class not found, etc.
➢ These errors are detected by the java compiler and an error message is displayed on the
screen while compiling.
➢ Compile Time Errors are sometimes also referred to as Syntax errors. These kind of
errors are easy to spot and rectify because the java compiler finds them for you.
➢ The compiler will tell you which piece of code in the program got in trouble and its best
guess as to what you did wrong.
➢ Usually, the compiler indicates the exact line where the error is, or sometimes the line
just before it, however, if the problem is with incorrectly nested braces, the actual error
may be at the beginning of the block. In effect, syntax errors represent grammatical
errors in the use of the programming language.
Logical Error: A logic error is when your program compiles and executes, but does the wrong
thing or returns an incorrect result or no output when it should be returning an output. These
errors are detected neither by the compiler nor by JVM.

Exception:
➢ 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.

What id Exception Handling


Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

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
Types Of Exception:

Exceptions can be categorized in two ways:


• Built-in Exceptions
Checked Exception
• Unchecked Exception
• User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
• Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.

• Unchecked 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.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
Java try and catch

➢ The try statement allows you to define a block of code to be tested for errors while it is
being executed.

➢ The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.

➢ SyntaxGet your own Java Server


try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Example

public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

}
Nested Try block in Exception:

➢ 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.

class NestedTry {

// main method
public static void main(String args[])
{
// Main try block
try {

// initializing array
int a[] = { 1, 2, 3, 4, 5 };

// trying to print element at index 5


System.out.println(a[5]);

// try-block2 inside another try block


try {

// performing division by zero


int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
}
}
// end of main method
}

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception types
available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Securit
yException, etc:
Example:

public class Main {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18 years old.");

else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

Finally Block

Used with try catch block

The finally block in java is used to put important codes such as clean up code e.g. closing the
file or closing the connection. The finally block executes whether exception rise or not and
whether exception handled or not. A finally contains all the crucial statements regardless of the
exception occurs or not.

Case 1: When an exception does not rise

Case 2: When the exception rises and handled by the catch block

Case 3: When exception rise and not handled by the catch block
class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}

// Can not accept Arithmetic type exception


// Only accept Null Pointer type Exception
catch (NullPointerException e) {

System.out.println(
"catch : exception not handled.");
}

// Always execute
finally {

System.out.println(
"finally : i will execute always.");
}
// This will not execute
System.out.println("i want to run");
}
}

Multithreading:

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.

1) Process-based Multitasking (Multiprocessing)

Each process has an address in memory. In other words, each process allocates a separate
memory area.

A process is heavyweight.

Cost of communication between the process is high.

Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)

Threads share the same address space.

A thread is lightweight.

Cost of communication between the thread is low.

Threads can be created by using two mechanisms :

1.Extending the Thread class

2.Implementing the Runnable Interface

1. 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.

class MultithreadingDemo extends Thread {

public void run()

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

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

2.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.

class MultithreadingDemo implements Runnable {

public void run()

{
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

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

}
}

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

Life Cycle of a Thread

There are multiple states of the thread in a lifecycle as mentioned below:

1. 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.
2. 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.

3. 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.
4. 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.
5. 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.
6. 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.

Implementing the Thread States in Java

In Java, to get the current state of the thread, use Thread.getState() method to get the current state
of the thread. Java provides java.lang.Thread.State class that defines the ENUM constants for the
state of a thread, as a summary of which is given below:

1. New

Thread state for a thread that has not yet started.

public static final Thread.State NEW

2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual
machine but it may be waiting for other resources from the operating system such as a processor.

public static final Thread.State RUNNABLE

3. Blocked

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is
waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized
block/method after calling Object.wait().

public static final Thread.State BLOCKED

4. Waiting

Thread state for a waiting thread. A thread is in the waiting state due to calling one of the
following methods:

Object.wait with no timeout

Thread.join with no timeout

LockSupport.park

public static final Thread.State WAITING

5. Timed Waiting

Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting
state due to calling one of the following methods with a specified positive waiting time:

Thread.sleep
Object.wait with timeout

Thread.join with timeout

LockSupport.parkNanos

LockSupport.parkUntil

public static final Thread.State TIMED_WAITING

6. Terminated

Thread state for a terminated thread. The thread has completed execution.

Declaration: public static final Thread.State TERMINATED

class thread implements Runnable {

public void run()

// moving thread2 to timed waiting state

try {

Thread.sleep(1500);

catch (InterruptedException e) {

e.printStackTrace();

System.out.println(

"State of thread1 while it called join() method on thread2 -"


+ Test.thread1.getState());

try {

Thread.sleep(200);

catch (InterruptedException e) {

e.printStackTrace();

public class Test implements Runnable {

public static Thread thread1;

public static Test obj;

public static void main(String[] args)

obj = new Test();

thread1 = new Thread(obj);

// thread1 created and is currently in the NEW

// state.

System.out.println(

"State of thread1 after creating it - "


+ thread1.getState());

thread1.start();

// thread1 moved to Runnable state

System.out.println(

"State of thread1 after calling .start() method on it - "

+ thread1.getState());

public void run()

thread myThread = new thread();

Thread thread2 = new Thread(myThread);

// thread1 created and is currently in the NEW

// state.

System.out.println(

"State of thread2 after creating it - "

+ thread2.getState());

thread2.start();

// thread2 moved to Runnable state

System.out.println(
"State of thread2 after calling .start() method on it - "

+ thread2.getState());

// moving thread1 to timed waiting state

try {

// moving thread1 to timed waiting state

Thread.sleep(200);

catch (InterruptedException e) {

e.printStackTrace();

System.out.println(

"State of thread2 after calling .sleep() method on it - "

+ thread2.getState());

try {

// waiting for thread2 to die

thread2.join();

catch (InterruptedException e) {

e.printStackTrace();

System.out.println(
"State of thread2 when it has finished it's execution - "

+ thread2.getState());

Thread Methods:

1. Wait()
2. Sleep()
3. Notify()
4. Resume()
5. Suspend()
6. Stop()

1. Wait():The wait() method releases the lock.


2. Sleep():It sleeps a thread for the specified amount of time.
3. Notify():It is used to give the notification for only one thread which is waiting for a
particular object.
4. Resume():It is used to resume the suspended thread.
5. Suspend():It is used to suspend the thread.
6. Stop():It is used to stop the thread.

Thread Exceptions:

1. IllegalArgumentException is thrown when the parametric value is negative as it is


bounded as discussed between [0 — +999999]
2. InterrupteException is thrown when a thread is interrupted with an ongoing thread as
discussed java supports the concepts of multithreading.

Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.

• Setter & Getter Method of Thread Priority


• Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of
the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method


updates or assign the priority of the thread to newPriority.

The method throws IllegalArgumentException if the value newPriority goes out of the range,
which is 1 (minimum) to 10 (maximum). constants defined in Thread class:

public static int MIN_PRIORITY

public static int NORM_PRIORITY

public static int MAX_PRIORITY

Why use Java Synchronization?

Java Synchronization is used to make sure by some synchronization method that only one thread
can access the resource at a given point in time.

Types of Synchronization

There are two synchronizations in Java mentioned below:

1. Process Synchronization
2. Thread Synchronization

1. 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.

2. 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)Inter-thread Communication in
Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

o 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:
o wait()
o notify()
o 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 imple3)

3) notifyAll() method

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

Deadlock in Java Multithreading

synchronized keyword is used to make the class or method thread-safe which means only one
thread can have lock of synchronized method and use it, other threads have to wait till the lock
releases and anyone of them acquire that lock.

It is important to use if our program is running in multi-threaded environment where two or more
threads execute simultaneously. But sometimes it also causes a problem which is called
Deadlock. Below is a simple example of Deadlock condition.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy