0% found this document useful (0 votes)
5 views24 pages

Attachment (2)

This document covers Java programming concepts related to exception handling and multi-threading. It explains the differences between errors and exceptions, the types of exceptions, and the mechanisms for handling them, including try-catch blocks and the use of keywords like throw and throws. Additionally, it discusses multithreading, including thread creation, lifecycle, and synchronization to ensure data consistency.

Uploaded by

adityapandji1
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)
5 views24 pages

Attachment (2)

This document covers Java programming concepts related to exception handling and multi-threading. It explains the differences between errors and exceptions, the types of exceptions, and the mechanisms for handling them, including try-catch blocks and the use of keywords like throw and throws. Additionally, it discusses multithreading, including thread creation, lifecycle, and synchronization to ensure data consistency.

Uploaded by

adityapandji1
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/ 24

Java Programming

Chapter 3 - K Scheme
Exception Handling & Multi-threading
Notes

Quote of the day: The expert in anything was once a beginner

Errors & Exception

Errors are severe issues that occur outside the control of the program. They usually indicate
problems related to the system or environment where the application is running. Since these
issues are critical, they are not meant to be handled within the code.

✅ Characteristics of Errors:

 Errors are represented by the Error class and its subclasses.


 Errors are unchecked, meaning they are not required to be declared in a method's
throws clause.
 Errors typically result in program termination.

✅ Common Types of Errors:

 StackOverflowError: Occurs when a recursive method calls itself endlessly.


 OutOfMemoryError: Occurs when the JVM runs out of memory.
 VirtualMachineError: Indicates that the JVM is unstable or has crashed.

Exceptions are events that occur during program execution that disrupt the normal flow of
instructions. They are caused by logical errors in the code and can be handled to ensure the
program continues running smoothly.

✅ Characteristics of Exceptions:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


 Exceptions are represented by the Exception class and its subclasses.
 Java provides two types of exceptions:
o Checked Exceptions (must be handled)
o Unchecked Exceptions (runtime errors)

Types of Errors in Java


Errors can be categorized into the following types:

1. Compile-Time Errors (Syntax Errors)

 Occur during code compilation.


 Caused by incorrect syntax, missing semicolons, incorrect variable declarations, etc.
 These errors prevent the program from running until they are fixed.

✅ Examples of Compile-Time Errors:

 Missing semicolon (;)


 Using undeclared variables
 Incorrect method signatures

Example of Compile-Time Error:

public class CompileTimeErrorExample {

public static void main(String[] args) {

int a = 10 // Error: Missing semicolon

System.out.println(a);

Error Output: ';' expected

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


2. Runtime Errors

 Occur while the program is running.


 These errors may occur due to invalid logic or incorrect user input.
 Commonly result in exceptions like NullPointerException, ArithmeticException, etc.

✅ Examples of Runtime Errors:

 Division by zero
 Accessing an invalid array index
 Dereferencing a null object

Example of Runtime Error:

public class RuntimeErrorExample {

public static void main(String[] args) {

int num = 5 / 0; // Error: ArithmeticException

System.out.println(num);

Exception Handling

Exception handling is a mechanism in Java used to manage errors that occur during program
execution. It ensures that the program continues running smoothly even when unexpected
situations arise.

What is an Exception?

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


An exception is an unexpected event that occurs during program execution, disrupting the
normal flow of instructions. In Java, exceptions are represented by the Exception class and its
subclasses.

✅ Examples of Common Exceptions:

 ArithmeticException – Dividing by zero.


 NullPointerException – Accessing an object that is null.
 ArrayIndexOutOfBoundsException – Accessing an invalid array index.
 IOException – Occurs during file handling errors.

Why Use Exception Handling?

 Prevents program crashes.


 Allows developers to handle unexpected errors gracefully.
 Improves code readability and debugging.

Exception Handling Keywords

Java provides five key keywords for exception handling:

1. try – Defines the block of code where an exception may occur.


2. catch – Handles the exception if it occurs in the try block.
3. finally – Executes code regardless of whether an exception occurred or not.
4. throw – Used to explicitly throw an exception.
5. throws – Declares exceptions that a method may throw.

1. try-catch Block

 The try block contains code that may cause an exception.


 The catch block handles that exception.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Syntax:

try {

// Code that may cause an exception

} catch (ExceptionType e) {

// Handling code

✅ Example of try-catch:

public class TryCatchExample {

public static void main(String[] args) {

try {

int result = 10 / 0; // Risky code: Division by zero

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero.");

System.out.println("Program continues...");

Output:

Error: Cannot divide by zero.

Program continues...

2. Multiple catch Blocks

If multiple exceptions can occur, each can be handled in separate catch blocks.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Example of Multiple catch Blocks:

public class MultipleCatchExample {

public static void main(String[] args) {

try {

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

System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {

System.out.println("Arithmetic error occurred.");

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array index is out of bounds.");

Output:

Array index is out of bounds.

3. finally Block

 The finally block always executes — whether an exception is thrown or not.


 It’s ideal for closing resources like files, databases, etc.

Syntax:

try {

// Code that may throw an exception

} catch (ExceptionType e) {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


// Exception handling code

} finally {

// Code that always executes

✅ Example of finally Block:

public class FinallyExample {

public static void main(String[] args) {

try {

int result = 5 / 0; // Risky code

} catch (ArithmeticException e) {

System.out.println("Error: Division by zero.");

} finally {

System.out.println("This block always executes.");

Output:

Error: Division by zero.

This block always executes.

4. throw Keyword

 The throw keyword is used to manually throw an exception.

Syntax:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


throw new ExceptionType("Error message");

✅ Example of throw Keyword:

public class ThrowExample {

public static void validateAge(int age) {

if (age < 18) {

throw new IllegalArgumentException("Age must be 18 or above.");

System.out.println("Access granted.");

public static void main(String[] args) {

validateAge(16); // Throws an exception

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or above.

5. throws Keyword

 The throws keyword is used in the method signature to declare exceptions that the
method might throw.

Syntax:

void method() throws ExceptionType {

// Code that may throw an exception

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}

✅ Example of throws Keyword:

import java.io.*;

public class ThrowsExample {

void readFile() throws IOException {

FileReader file = new FileReader("nonexistentfile.txt");

public static void main(String[] args) {

try {

new ThrowsExample().readFile();

} catch (IOException e) {

System.out.println("File not found: " + e.getMessage());

Built-in Exception

Java provides a rich set of built-in exceptions to handle common runtime errors. These
exceptions are part of the java.lang package, which is automatically imported in every Java
program.

Hierarchy of Exceptions in Java

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


All exception classes are derived from the Throwable class. The key branches are:

 Exception – Used for recoverable conditions (handled with try-catch).


 Error – Used for serious issues that the program cannot typically recover from.

Throwable

├── Exception

│ ├── IOException

│ ├── SQLException

│ ├── RuntimeException

│ ├── ArithmeticException

│ ├── NullPointerException

│ ├── ArrayIndexOutOfBoundsException

│ ├── IllegalArgumentException

│ └── NumberFormatException

└── Error

├── OutOfMemoryError

├── StackOverflowError

└── VirtualMachineError

Types of Built-in Exceptions

Java exceptions are broadly classified into two types:

1. Checked Exceptions (Compile-Time Exceptions)


2. Unchecked Exceptions (Runtime Exceptions)

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


1. Checked Exceptions (Compile-Time Exceptions)

 Checked exceptions are checked at compile time.


 If these exceptions are not handled, the program will fail to compile.
 Typically occur during file handling, database operations, etc.

✅ Common Checked Exceptions:

Exception Description

IOException Occurs when there’s an issue with input-output operations.

SQLException Occurs when there’s an error in SQL queries.

ClassNotFoundException Occurs when a class is not found in the classpath.

InterruptedException Occurs when a thread is interrupted while sleeping or waiting.

Example of Checked Exception:

import java.io.*;

public class CheckedExceptionExample {

public static void main(String[] args) {

try {

FileReader file = new FileReader("file.txt"); // File may not exist

} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

Output:

File not found: file.txt (The system cannot find the file specified)

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


2. Unchecked Exceptions (Runtime Exceptions)

 Unchecked exceptions are not checked at compile time.


 These exceptions occur during program execution due to programming logic errors.

✅ Common Unchecked Exceptions:

Exception Description

Occurs when arithmetic operations go wrong (e.g., divide


ArithmeticException
by zero).

Occurs when trying to access an object reference that is


NullPointerException
null.

ArrayIndexOutOfBoundsException Occurs when an invalid array index is accessed.

Occurs when trying to convert invalid string data into a


NumberFormatException
numeric format.

Occurs when a method receives an inappropriate


IllegalArgumentException
argument.

Example of Unchecked Exceptions:

1. ArithmeticException Example:

public class ArithmeticExceptionExample {

public static void main(String[] args) {

int num = 10 / 0; // Division by zero

System.out.println(num);

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Multi-Threading

Multithreading is a programming technique in Java that allows multiple parts of a program


(called threads) to run concurrently. It enhances the performance and responsiveness of
applications by executing multiple tasks simultaneously.

Key Concepts in Multithreading

1. Thread: A lightweight process that executes independently.


2. Main Thread: Every Java program starts with a default main thread.
3. Concurrency: The ability to run multiple threads simultaneously.
4. Parallelism: The true simultaneous execution of threads on multi-core processors.

Life Cycle of a Thread

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


A thread goes through several stages during its execution:

1. New → Created but not started yet.


2. Runnable → Ready to run but waiting for CPU time.
3. Blocked → Waiting for a resource to become available.
4. Waiting → Waiting indefinitely for another thread’s signal.
5. Timed Waiting → Waiting for a specific time before resuming.
6. Terminated → Execution is complete.

Creating Threads in Java

There are two main ways to create a thread in Java:

1. By Extending the Thread class


2. By Implementing the Runnable interface

1. Creating a Thread by Extending Thread Class

In this method, you create a class that extends the Thread class and override its run() method.

✅ Example Using Thread Class:

class MyThread extends Thread {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


public void run() {

for(int i = 1; i <= 5; i++) {

System.out.println("Thread: " + i);

try {

Thread.sleep(1000); // Pause for 1 second

} catch (InterruptedException e) {

System.out.println(e.getMessage());

public class ThreadExample {

public static void main(String[] args) {

MyThread t1 = new MyThread(); // Creating thread instance

t1.start(); // Starting the thread

Output:

Thread: 1Thread: 2Thread: 3Thread: 4Thread: 5

2. Creating a Thread by Implementing Runnable Interface

This method is preferred in Java because it avoids the limitation of extending only one class.

✅ Example Using Runnable Interface:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


class MyRunnable implements Runnable {

public void run() {

for(int i = 1; i <= 5; i++) {

System.out.println("Runnable Thread: " + i);

try {

Thread.sleep(1000); // Pause for 1 second

} catch (InterruptedException e) {

System.out.println(e.getMessage());

public class RunnableExample {

public static void main(String[] args) {

MyRunnable myRunnable = new MyRunnable(); // Creating Runnable object

Thread thread = new Thread(myRunnable); // Passing Runnable to Thread

thread.start(); // Starting the thread

Output:

Runnable Thread: 1Runnable Thread: 2Runnable Thread: 3Runnable Thread: 4Runnable


Thread: 5

Thread Methods in Java

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Java provides several useful thread methods:

Method Description

start() Starts the thread and calls run()

run() Contains the code that the thread will execute

sleep(milliseconds) Pauses thread execution for a specified time

join() Forces the current thread to wait for another thread to finish

Pauses the current thread to allow other threads of the same priority to
yield()
execute

isAlive() Checks if the thread is still running

setPriority() Sets thread priority (1 to 10)

getName() /
Gets/Sets the thread's name
setName()

Example Using join() and sleep() Methods


class MyThread extends Thread {

public void run() {

for(int i = 1; i <= 3; i++) {

System.out.println(Thread.currentThread().getName() + " - " + i);

try {

Thread.sleep(1000); // Pause for 1 second

} catch (InterruptedException e) {

System.out.println(e.getMessage());

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}

public class JoinExample {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

t1.start();

try {

t1.join(); // Main thread waits for t1 to finish before starting t2

} catch (InterruptedException e) {

System.out.println(e.getMessage());

t2.start();

Output:

Thread-0 - 1Thread-0 - 2Thread-0 - 3Thread-1 - 1Thread-1 - 2Thread-1 - 3

Thread Synchronization

Synchronization prevents multiple threads from accessing the same resource simultaneously,
ensuring data consistency.

✅ Example of Synchronization in Java:

class Counter {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


int count = 0;

// Synchronized method to ensure one thread modifies count at a time

synchronized void increment() {

count++;

public class SyncExample {

public static void main(String[] args) {

Counter counter = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

counter.increment();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

counter.increment();

});

t1.start();

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


t2.start();

try {

t1.join();

t2.join();

} catch (InterruptedException e) {

System.out.println(e.getMessage());

System.out.println("Final Count: " + counter.count);

Output:

Final Count: 2000

Without synchronization, the count may result in incorrect values due to thread interference.

Advantages of Multithreading

✅ Improves application performance through concurrency.


✅ Efficient CPU utilization by running multiple tasks in parallel.
✅ Enables faster execution in real-time applications.
✅ Ensures responsive UI by handling background tasks in GUI applications.

Disadvantages of Multithreading

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


❗ Increases complexity in program design.
❗ Synchronization issues may arise, leading to race conditions.
❗ Difficult to debug thread-related issues.

Common Use Cases of Multithreading

✅ Gaming applications.
✅ Real-time systems like GPS or navigation apps.
✅ GUI-based applications where background tasks must run smoothly.
✅ Server-based applications handling multiple client requests.

Deadlock in Java

A deadlock is a situation in which two or more threads are blocked forever, each waiting for
the other to release a resource. It typically occurs when multiple threads hold some shared
resources and try to acquire the resources that are held by other threads.

How Deadlock Occurs?

Deadlock happens when these four conditions are met:

1. Mutual Exclusion: Only one thread can access a resource at a time.


2. Hold and Wait: A thread holding one resource waits for another resource held by a
different thread.
3. No Preemption: Resources cannot be forcibly taken from a thread; they can only be
released voluntarily.
4. Circular Wait: A circular chain of threads exists, where each thread waits for a
resource held by the next thread in the chain.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Deadlock Example in Java
class Resource {

synchronized void methodA(Resource resource) {

System.out.println(Thread.currentThread().getName() + " is executing methodA");

try {

Thread.sleep(1000); // Simulate some work

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName() + " is waiting for methodB");

resource.methodB(this); // Triggers circular wait

synchronized void methodB(Resource resource) {

System.out.println(Thread.currentThread().getName() + " is executing methodB");

try {

Thread.sleep(1000); // Simulate some work

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName() + " is waiting for methodA");

resource.methodA(this); // Triggers circular wait

public class DeadlockExample {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


public static void main(String[] args) {

Resource resource1 = new Resource();

Resource resource2 = new Resource();

Thread t1 = new Thread(() -> resource1.methodA(resource2), "Thread 1");

Thread t2 = new Thread(() -> resource2.methodB(resource1), "Thread 2");

t1.start();

t2.start();

Output:
Thread 1 is executing methodA

Thread 2 is executing methodB

Thread 1 is waiting for methodB

Thread 2 is waiting for methodA

Both threads are now stuck in an infinite wait — a deadlock situation.

How to Prevent Deadlock?

Here are some effective techniques to avoid deadlock in Java:

✅ Avoid Nested Locks: Minimize locking multiple resources at once.


✅ Lock Ordering: Always acquire locks in a specific order across all threads.
✅ Timeouts: Use timeouts while waiting for a lock to prevent infinite blocking.
✅ Try-Lock Mechanism: The tryLock() method in ReentrantLock can help avoid deadlock
by attempting to acquire a lock for a specified time.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND

You might also like