Exception Handling and Multithreading inJava Programming

roshphilip19 5 views 54 slides Sep 17, 2025
Slide 1
Slide 1 of 54
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54

About This Presentation

Exception Handling and Multithreading inJava Programming


Slide Content

Module 3 EXCEPTION HANDLING AND MULTITHREADING 1

Exception handling in JAVA Exception handling in Java is designed to manage runtime errors and maintain the normal flow of an application.  It allows programs to gracefully handle unexpected events, preventing abrupt termination and ensuring a more stable and user-friendly experience. Exception handling in Java is a powerful mechanism that allows developers to manage runtime errors and ensure the smooth flow of program execution . 2

Reason for Why an Exception Occurs? Exceptions can occur due to between several reasons, such as: Invalid user input Device failure Loss of network connection Physical limitations (out-of-disk memory) Code errors Out of bound Null reference Type mismatch Opening an unavailable file Database errors Arithmetic errors 3

Types of Java Exceptions Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their it's exceptions. 4

Built-in Exception Build-in Exception are pre-defined exception classes provided by Java to handle common errors during program execution. 1. Checked Exceptions Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. ClassNotFoundException : Throws when the program tries to load a class at runtime but the class is not found because it's belong not present in the correct location or it is missing from the project. InterruptedException : Thrown when a thread is paused and another thread interrupts it. 5

Built-in Exception IOException : Throws when input/output operation fails. InstantiationException : Thrown when the program tries to create an object of a class but fails because the class is abstract, an interface, or has no default constructor. SQLException : Throws when there is an error with the database. FileNotFoundException : Thrown when the program tries to open a file that does not exist. 6

Unchecked Exceptions ArithmeticException : It is thrown when there is an illegal math operation. ClassCastException : It is thrown when we try to cast an object to a class it does not belong to. NullPointerException : It is thrown when we try to use a null object (e.g. accessing its methods or fields). ArrayIndexOutOfBoundsException : This occurs when we try to access an array element with an invalid index. ArrayStoreException : This happens when we store an object of the wrong type in an array. IllegalThreadStateException : It is thrown when a thread operation is not allowed in its current state. 7

2. User-Defined Exception 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". 8

Try-Catch Block A try-catch block in Java is a mechanism to handle exception. The try block contains code that might thrown an exception and the catch block is used to handle the exceptions if it occurs. 9

finally Block The finally block is used to execute important code regardless of whether an exception occurs or not. Note : finally block is always executes after the try-catch block. It is also used for resource cleanup. 10

 Exception Handling Keywords Java provides a robust mechanism for handling runtime errors using  exception handling . The primary keywords used are: try catch throw throws finally 11

try / catch block in Exceptional handling try / catch block The try block  encloses code that might throw an exception . It must be followed by  at least one  catch  or  finally  block . Catches and handles exceptions thrown in the  try  block. Multiple  catch  blocks can be used to handle different exception 12

Multiple catch Blocks Multiple catch blocks handle different exception types The first exception encountered (array index out of bounds) triggers its handler Subsequent potential exceptions in try block aren't executed because control jumps to catch Array index out of bounds! Output: Array index out of bounds! 13

throw Keyword (Custom Exception) throw explicitly throws an exception object We created a new ArithmeticException with a custom message The exception propagates up to the calling method's catch block Useful for enforcing business rules (like age validation) Output: Exception caught: Not valid - must be at least 18 years old. 14

throws Exception throws declares that a method might throw certain exceptions Callers must handle or declare these exceptions File operations commonly throw IOException Forces explicit exception handling in calling code Output: File not found: test.txt (The system cannot find the file specified) 15

finally Block finally executes whether an exception occurs or not Critical for resource cleanup (closing files, DB connections) Runs even if there's a return statement in try/catch Only doesn't run if JVM exits ( System.exit ()) or thread dies Sample Output (valid input): Enter a number: 9 Square root: 3.0 This block always executes. Sample Output (invalid input): Enter a number: abc Invalid input! Please enter a number. This block always executes. 16

Checked Exception - ClassNotFoundException Occurs when: The Java Virtual Machine (JVM) cannot find a specified class during runtime. Loading a class using Class.forName () Missing JAR files in classpath Typographical errors in class names A database driver class not found when establishing JDBC connection. This occurs when trying to load a class that isn't available in the classpath . Output: Class not found: com.example.NonExistentClass 17

Checked Exception - InterruptedException Occurs when: A thread is interrupted while it's in a waiting, sleeping, or otherwise occupied state. Thread.sleep () Object.wait () Thread.join () If another thread interrupts the sleeping thread, the sleep() method throws this exception . Output: Thread was interrupted: sleep interrupted 18

Checked Exception -   IOException Occurs when: An input/output operation fails or is interrupted. FileNotFoundException - File operations EOFException - unexpected end of file or end of stream has been reached during an input operation. SocketException - Network communications IO error occurred: test.txt (The system cannot find the file specified) Output: IO error occurred: test.txt (The system cannot find the file specified) 19

Checked Exception - InstantiationException Occurs when : Trying to create an instance of a class that cannot be instantiated. The class is abstract The class is an interface The class doesn't have an accessible no- arg constructor The code tries to create an instance of an abstract class using reflection, which is not allowed. Output: Cannot instantiate: InstantiationExample$AbstractClass 20

Checked Exception -   SQLException Occurs when: Database access errors or other relational database problems occur. SQL state (standardized error code) - Invalid SQL queries Vendor-specific error code - Connection failures Chained exceptions - Constraint violations The connection to the MySQL database fails due to invalid credentials or missing database. Output: Database error: Access denied for user ' user'@'localhost ' (using password: YES) SQL State: 28000 (28 = Invalid authorization specification, 000 = No subclass specified) Error Code: 1045 ("Access denied for user") 21

Checked Exception – FileNotFoundException Occurs when : An attempt to open a file denoted by a specified pathname fails. File doesn't exist No read permissions Path is actually a directory The program attempts to open a non-existent file. Output: File not found: missing.txt (The system cannot find the file specified) 22

Characteristics of Checked Exceptions Characteristics of Checked Exceptions: Compile-time checking: The Java compiler verifies proper handling. Recoverable conditions: Represent situations where recovery might be possible. Method signature declaration: Must be declared using throws if not caught. External factors: Often related to resources outside program control (files, networks, databases). Documentation: Properly documented exceptions are part of a method's contract. Why Checked Exceptions Matter: Forces error handling: Developers must explicitly handle potential problems. Improves code reliability: Makes failure conditions visible in the code. Better API design: Clearly communicates what can go wrong. Separation of concerns: Different from programming errors (unchecked exceptions). 23

Unchecked Exceptions - ArithmeticException Occurs during invalid arithmetic operations Most common case: division by zero Subclass of RuntimeException Indicates programming logic errors Any number is not divisible by zero 24 Output: Error: / by zero

Unchecked Exceptions - NullPointerException Occurs when trying to use null where an object is required Common with uninitialized object references Subclass of RuntimeException Can be prevented with null checks This NullPointerException occurs when trying to call the length() method that is null instead of containing an actual string object. 25 Output: Error: Cannot invoke " String.length ()" because "text" is null

Unchecked Exceptions -   ArrayIndexOutOfBoundsException Occurs when accessing invalid array indices Triggered by negative indices or indices ≥ array length Subclass of IndexOutOfBoundsException Indicates boundary violation errors Trying to access beyond the array limit 26 Output: Error: Index 5 out of bounds for length 3

Multi threading in JAVA Multithreading in Java is a feature that enables the concurrent execution of multiple parts of a program, known as threads , within a single process.  This allows for improved CPU utilization and responsiveness , as different tasks can run seemingly simultaneously. Multithreading  is a Java feature that enables the concurrent execution of two or more parts of a program , maximizing CPU utilization. Threads are lightweight processes within a process representing the smallest unit of execution within a program.  Threads within the same process share the same memory space , which contributes to their efficiency compared to separate processes . 27

Multithreading Example Imagine a restaurant kitchen where multiple chefs are working simultaneously on different dishes. This setup ensures faster service and better CPU (chef) utilization, just like threads in Java. 28

Java Thread Model The Java Thread Model is based on the concept of multithreading , where multiple threads (lightweight sub-processes) run concurrently within a program. This allows better utilization of CPU resources and improves performance for tasks that can run in parallel. Key Features of Java Thread Model Preemptive Multitasking: The Java thread scheduler decides which thread to run at any given time based on priority and availability. Concurrency: Multiple threads share the same memory space , enabling communication and data sharing easily. Lightweight Threads: Threads share the process resources (memory, open files) but have their own execution stack, program counter, and registers. Platform Independence: Thread behavior is implemented in the JVM , making Java's multithreading platform-independent. 29

Thread States in Java Threads in Java have the following states (defined in NEW – When a thread is created but not yet started. RUNNABLE – Ready to run, waiting for CPU time. RUNNING – Actively executing. BLOCKED – Waiting to acquire a lock (for synchronization). WAITING – Waiting indefinitely for another thread's signal. TIMED_WAITING – Waiting for a specified time. TERMINATED – Thread has finished execution. 30 java.lang.Thread.State is an enumeration in Java that defines the possible states a thread can be in at any given point during its lifecycle. These states are managed by the Java Virtual Machine (JVM) and provide insights into the thread's activity.

Thread Creation By Extending Thread class: By Implementing Runnable interface: 31 Output: Thread running...

Multithread Creation 32

Multithreading in JAVA 33

Thread Methods in JAVA Method Description start() Starts the thread by calling its run() method. Multi-client server : Each client connection is handled in a separate thread. Example: Chat server, web server. run() Entry point for the thread. Like printing reports, sending emails, or background calculations. sleep( ms ) Pauses the thread for a given time. A thread that fetches updated data from the server every 10 seconds. Game timer or traffic light simulation join() Waits for a thread to die. Ensure authentication thread finishes before accessing the user profile. yield() Hints the thread scheduler to pause and give other threads equal opportunity. In a multi-threaded game, yield can let rendering threads share time fairly with background threads. isAlive () Checks if thread is still running. Continuously checks if a background task is still running to update the UI. 34

Thread Priority in JAVA Thread priority is a number assigned to each thread , indicating how important it is relative to other threads. It influences , but does not guarantee , the order in which threads are scheduled for execution. Java provides a priority-based scheduling mechanism where threads with higher priority are more likely to be executed before lower-priority threads. 35 Constant Value Meaning Thread.MIN_PRIORITY 1 Lowest priority Thread.NORM_PRIORITY 5 Default/normal priority Thread.MAX_PRIORITY 10 Highest priority

Muli threading Concepts Thread Synchronization Multiple threads accessing shared data may cause inconsistencies . Java provides: Synchronized Methods Synchronized Blocks synchronized void display() { // critical section } Ensures mutual exclusion , allowing only one thread to access the method or block at a time. Daemon Threads Background threads that support main threads. Automatically terminates when all user threads finish. Thread t = new Thread(); t.setDaemon (true); 36

Thread Life Cycle 37

Thread Life Cycle 1. New The thread is created but has not started yet. Object is created using Thread t = new Thread(); Transition : start() → moves the thread to the Runnable state. 2. Runnable The thread is ready to run , but it’s waiting for CPU time . It may be in the runnable queue . Transition : run() → called by JVM when the thread is picked by the scheduler. yield() → gives chance to other threads of equal priority. resume() or notify() can move a blocked thread here.   38

Thread Life Cycle 3. Running The thread is currently being executed by the CPU . sleep(), wait(), or suspend() → moves to Blocked . yield() → goes back to Runnable . When execution completes or stop() is called → moves to Dead .   4. Blocked (Waiting / Not Runnable) Thread is paused or waiting for a resource or condition . Cannot run until it is resumed or notified . sleep() → Temporarily paused for a set time. wait() → Waiting for a condition or monitor lock. suspend() → Paused explicitly (deprecated now). notify(), notifyAll (), or resume() → moves back to Runnable .   5. Dead The thread has finished execution or has been stopped forcibly . Caused by : Method execution completes normally. stop() is called to terminate the thread (deprecated).   39

Thread Priorities In Java, thread priorities are used to indicate to the thread scheduler how important a thread is relative to other threads. The scheduler tends to give higher priority threads more CPU time than lower priority ones, though the exact behavior depends on the underlying operating system. Priority Levels Java provides 3 constants and a range of priority values: MIN_PRIORITY (constant 1) - Lowest priority NORM_PRIORITY (constant 5) - Default priority MAX_PRIORITY (constant 10) - Highest priority The priority range is from 1 (lowest) to 10 (highest). 40

Thread Priorities 41

Synchronization in Multithreading In Java, thread synchronization is the process of controlling the access of multiple threads to shared resources (variables, methods, or objects) to prevent data inconsistency and race conditions . When multiple threads try to access and modify the same resource at the same time, unexpected results may occur. Synchronization ensures that only one thread can access the resource at a time. Why Synchronization is Needed Without synchronization, you can face problems like: Race Condition – When two or more threads compete to update a shared variable, results depend on the timing of execution. Data Inconsistency – Shared data may become corrupt if multiple threads modify it without coordination. Deadlock risk – Poor synchronization can also cause deadlocks (threads waiting forever). 42

Without Synchronization in Multithreading 43

With Synchronization in Multithreading It locks the resource so that only one thread can access it at a time. Now only one thread can execute increment() at a time. 1. Synchronized Method Instead of locking the whole method, you can lock only the critical section: This improves performance because other non-critical parts can still run concurrently. 2. Synchronized Block 44

Thread Synchronization issues Thread Synchronization Problems Even with synchronization, you may encounter: Deadlock: Two threads wait for each other’s lock forever. Starvation: A thread never gets CPU time because other threads keep acquiring locks. Livelock : Threads keep changing states in response to each other but make no progress. Real-Life Example Imagine two bank ATMs updating the same account balance: Without synchronization → One ATM deducts money, another deducts at the same time, and the balance becomes wrong. With synchronization → Only one ATM transaction updates at a time, ensuring the correct balance. 45

Inter-Thread Communication Inter-thread communication in Java is the mechanism that allows multiple threads to share resources and coordinate their actions without interfering with each other in a harmful way. If multiple threads are working together (e.g., a producer thread creating data and a consumer thread processing it), they must avoid: Race conditions (two threads changing the same data at the same time) Busy waiting (one thread constantly checking if the other is done, wasting CPU) When multiple threads work together: One thread may need to wait until another finishes some task. We want to avoid busy waiting (where a thread keeps checking repeatedly if it can proceed, wasting CPU). We want a safe, synchronized way for threads to exchange data. 46

Producer Consumer Problem The Producer thread produces data and puts it in a buffer. The Consumer thread takes data from the buffer. The producer must wait if the buffer is full. The consumer must wait if the buffer is empty. Only one thread ( either Producer or Consumer) can access the shared buffer at a time. Achieved using synchronized blocks or locks. Producer cannot add more items than the buffer can hold. Consumer cannot remove items when the buffer is empty. 47

Methods used for Inter-Thread Communication wait() Causes the current thread to wait until another thread calls notify() or notifyAll () on the same object. Releases the lock (monitor) on the object so other threads can enter synchronized blocks. Must be called inside a synchronized block/method. notify() Wakes up one thread waiting on the object’s monitor. Does not release the lock immediately — lock is released after the synchronized block ends. notifyAll () Wakes up all threads waiting on the object’s monitor. They compete for the lock; only one gets it at a time. 48

Producer – Consumer Program in JAVA 49 Output:

Inter thread communication in Real time applications Message Queues: Producers generate messages, consumers process them Printer Queues: Computers send print jobs, printer processes them one by one. Logging Systems: Application threads log messages, a logging thread writes to file or DB. Multiplayer Game Servers: Game events are produced and sent to clients in sync. Web Servers: Worker threads process requests, response threads send them to clients. IoT Sensor Systems: Sensor reading threads send data to processing threads. Media Streaming: Download thread buffers video, playback thread consumes it. 50

Deadlock in Multithreading A deadlock is a situation in multithreading where two or more threads are blocked forever, each waiting for the other to release a resource. Once in a deadlock, the threads involved can never make progress without external intervention (like killing the process). How Deadlock happens Deadlock typically occurs when: Threads hold at least one resource (like an object lock) They request another resource that’s already held by another thread None of them release their current resource until they get the new one This creates a circular waiting chain Thread A has Lock 1, wants Lock 2 Thread B has Lock 2, wants Lock 1 Both keep waiting for the other → deadlock. 51

Four Necessary Conditions for Deadlock Mutual Exclusion Only one thread can access a resource at a time. Hold and Wait A thread holds one resource while waiting for another. No Preemption A resource can’t be forcibly taken from a thread; it must be released voluntarily. Circular Wait A set of threads are each waiting for a resource held by the next thread in the chain. If you break any one of these conditions, deadlock cannot occur. 52

Deadlock Example program 53 Output:

Real time application in Deadlock 1. Database Systems Multiple transactions lock different tables/rows and then wait for each other. Transaction A locks Accounts table and waits for Transactions table. Transaction B locks Transactions table and waits for Accounts table. 2. File Processing Systems Two threads lock different files and then try to access each other’s file. One thread locks file1.txt and waits for file2.txt. Another thread locks file2.txt and waits for file1.txt. 3. Multithreaded Applications with Shared Resources Multiple threads acquire locks on different objects in different orders. Thread A locks Printer then waits for Scanner. Thread B locks Scanner then waits for Printer. 4. Banking Systems Two accounts being updated in opposite order by two separate transactions. Account transfer logic locks “From” account first in one thread and “To” account first in another. 54
Tags