UNIT 3 Object Oriented Programming
UNIT 3 Object Oriented Programming
Programming
UNIT III
UNIT III EXCEPTION HANDLING AND MULTITHREADING
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in Exceptions – User
defined Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple Threads –
Priorities – Synchronization – Inter Thread Communication Suspending –Resuming, and Stopping Threads –
Multithreading. Wrappers – Auto boxing.
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Here’s the basic syntax:
try
{
// Code that may throw an exception
}
catch (ExceptionType e)
{
// Code to handle the exception
}
finally
{
// Optional block that executes after try/catch, regardless of whether an
exception occurred
}
EXCEPTION HANDLING IN JAVA
class expExample {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
EXCEPTION HANDLING IN JAVA
class expExample { Output
public static void main(String[] args) { ArithmeticException => / by zero
try { This is the finally block
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
public static void main(String[] args) {
// Test with an invalid age
// Custom Exception Class
try {
class AgeNotValidException extends Exception {
validate(15); // This will throw an
public AgeNotValidException(String message) {
exception
super(message);
} catch (AgeNotValidException e) {
}
System.out.println("Error: " +
}
e.getMessage());
}
// Main Class
public class AgeValidator {
// Test with a valid age
// Method to validate age
try {
public static void validate(int age) throws AgeNotValidException
validate(20); // This will pass
{
} catch (AgeNotValidException e) {
if (age < 18) {
System.out.println("Error: " +
throw new AgeNotValidException("Age must be 18 or
e.getMessage());
older.");
}
}
}
System.out.println("Valid age: " + age);
}
}
EXCEPTION HANDLING IN JAVA
Exception handling in Java (and in programming in general) provides several key benefits:
OutOfMemoryError,
Examples IOException, NullPointerException
StackOverflowError
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Checked Exceptions
Checked exceptions are exceptions that are checked at compile time. The compiler requires you to handle or declare them.
1. IOException: Thrown when an I/O operation fails or is interrupted.
2. SQLException: Thrown when there is an error accessing a database.
3. ClassNotFoundException: Thrown when a class cannot be located.
4. FileNotFoundException: A subclass of IOException, thrown when a file with the specified pathname does not exist.
5. InterruptedException: Thrown when a thread is waiting, sleeping, or otherwise occupied, and another thread interrupts it.
6. ParseException: Thrown when parsing a string into a number or date fails.
7. InstantiationException: Thrown when an application tries to create an instance of a class using the newInstance()
method but the class cannot be instantiated.
Unchecked Exceptions
Unchecked exceptions are not checked at compile time. They are subclasses of RuntimeException and typically indicate
programming errors.
8. NullPointerException: Thrown when trying to use a null reference where an object is required.
9. ArrayIndexOutOfBoundsException: Thrown when trying to access an invalid index of an array.
10. ArithmeticException: Thrown when an arithmetic operation fails, such as dividing by zero.
11. ClassCastException: Thrown when an invalid cast is attempted.
12. IllegalArgumentException: Thrown when a method receives an argument that is not acceptable.
13. NumberFormatException: Thrown when a string cannot be converted to a numeric type.
14. IndexOutOfBoundsException: Thrown when trying to access an invalid index in a collection, such as a list or string.
EXCEPTION HANDLING IN JAVA
EXAMPLES OF EXCEPTIONS
IN JAVA
EXCEPTION HANDLING IN JAVA
1. NullPointerException
Occurs when trying to access a method or variable on an object that is null.
Example:
Example:
Example:
In Java, nested try statements refer to the situation where one try-catch block is placed inside another try
block. This structure allows handling different exceptions that may arise in different parts of a program, especially in
scenarios where a specific exception can occur within another exception-prone code section.
EXCEPTION HANDLING IN JAVA
syntax for nested try-catch statements
try {
// Outer try block
// Code that may throw exceptions
try {
// Inner try block
// Code that may throw exceptions inside the inner try block
}
catch (ExceptionType1 e1) {
// Inner catch block for ExceptionType1
}
try {
// Another inner try block (optional)
// More code that may throw exceptions
}
catch (ExceptionType2 e2) {
// Inner catch block for ExceptionType2
}
// More code in the outer try block
}
catch (ExceptionType3 e3) { // Outer catch block for ExceptionType3 }
finally {
// Finally block for cleanup (optional)
// This will always execute, regardless of whether an exception occurred or not }
EXCEPTION HANDLING IN JAVA
public class NestedTryExample {
public static void main(String[] args) {
// Outer try block
try {
int[] numbers = {1, 2, 3};
// Nested (inner) try block 1
try {
System.out.println("Accessing index 5 of the array: " + numbers[5]);
// ArrayIndexOutOfBoundsException }
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException in inner try block 1: " +
e.getMessage()); }
// Nested (inner) try block 2
try {
int result = 10 / 0; // ArithmeticException
}
catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException in inner try block 2: " + e.getMessage());
}
// This line will still execute even if exceptions occur above
System.out.println("After inner try blocks."); }
catch (Exception e) {
// Outer catch block to catch any remaining exceptions
System.out.println("Caught exception in outer try block: " + e.getMessage());
}
finally {
System.out.println("Finally block always executes, at the end of all try-catch blocks.");
} } }
EXCEPTION HANDLING IN JAVA
OUTPUT
1. NullPointerException
○ Thrown when a program attempts to access an object through a null
reference.
Example:
System.out.println(text.length());
// Throws NullPointerException
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS
2. ArithmeticException
● Thrown when an illegal arithmetic operation occurs, such as division by zero.
Example:
int result = 10 / 0;
// Throws ArithmeticException
3. ArrayIndexOutOfBoundsException
● Thrown when trying to access an invalid index of an array.
Example:
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws
ArrayIndexOutOfBoundsException
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS
4. ClassCastException
● Thrown when an object is cast to a class that it is not an instance of.
Example:
Object obj = new Integer(5);
String str = (String) obj; // Throws ClassCastException
5. NumberFormatException
● Thrown when an attempt to convert a string to a numeric type fails.
Example:
String num = "abc";
int n = Integer.parseInt(num);
// Throws NumberFormatException
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS
6. IllegalArgumentException
○ Thrown when a method receives an argument that is inappropriate or not expected.
7. IndexOutOfBoundsException
○ Thrown when attempting to access an invalid index in a list or array.
■ Subtypes: ArrayIndexOutOfBoundsException and
StringIndexOutOfBoundsException.
8. IllegalStateException
○ Thrown when a method is invoked at an illegal or inappropriate time, often because
an object is in an improper state.
9. UnsupportedOperationException
○ Thrown when an unsupported method is invoked (often in collections).
EXCEPTION HANDLING IN JAVA
JAVA BUILT IN EXCEPTIONS
Error Class
Errors in Java represent serious issues, often related to the environment (JVM) rather than the
program itself. These are not meant to be caught by typical applications.
Common Errors:
1. StackOverflowError
○ Thrown when the stack memory allocated to a program is exceeded, typically due to
deep recursion.
2. OutOfMemoryError
○ Thrown when the JVM runs out of memory to allocate new objects.
3. VirtualMachineError
○ A superclass for errors related to the JVM, such as OutOfMemoryError and
StackOverflowError.
4. AssertionError
○ Thrown when an assertion fails, usually when the -ea (enable assertions) flag is used
during runtime.
EXCEPTION HANDLING IN JAVA
USER DEFINED EXCEPTIONS IN JAVA
OUTPUT
What is a Thread?
● A thread is a lightweight process that allows multiple operations to execute
concurrently within a single program.
● Concurrency enables more efficient CPU usage and improved program
responsiveness.
Thread Definition:
A thread is the smallest unit of a program that can be scheduled for execution by the
operating system.
Key Characteristics of a Thread:
● Shares resources like memory and file handles with other threads within the
same process.
● Each thread has its own execution context (stack, program counter, etc.).
MULTITHREADING IN JAVA
JAVA THREADS
Thread Concepts
● Main Thread:
Every Java application starts with a main thread, which is created
automatically by the JVM.
● Creating Threads:
Threads can be created in Java by:
○ Extending the Thread class.
○ Implementing the Runnable interface.
MULTITHREADING IN JAVA
JAVA THREADS
MULTITHREADING IN JAVA
EXAMPLE
class CurrentThreadDemo {
public static void main(String args[]) {
// Get the reference to the current thread (main thread)
Thread t =
Thread.currentThread();
// Print information about the current thread
OUTPUT
We can create threads by instantiating an object of type Thread. Java defines two
ways
to create threads:
1. By implementing Runnable interface (java.lang.Runnable)
2. By extending the Thread class (java.lang.Thread)
Example: Creating Threads by Implementing the Runnable Interface
// Step 1: Create a class that implements the Runnable interface
class MyRunnable implements Runnable {
// Step 2: Override the run() method
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i + " - Thread is running by implementing Runnable
interface");
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}}}}
public class TestRunnable {
public static void main(String[] args) {
// Step 3: Create an instance of the MyRunnable class
MyRunnable myR = new
MyRunnable();
// Step 4: Create a Thread object and pass MyRunnable to the Thread constructor
Thread t1 = new Thread(myR);
// Step 5: Start the thread using the start() method
t1.start(); } }
MULTITHREADING IN JAVA
OUTPUT
Here’s a list of the commonly used methods of the Thread class in Java:
1. void start()
2. void run()
3. static void sleep(long milliseconds)
4. void join()
5. void join(long millis)
6. void setPriority(int priority)
7. int getPriority()
8. static Thread currentThread()
9. void setName(String name)
10.String getName()
11.boolean isAlive()
12.void yield()
13.void interrupt()
14.boolean isInterrupted()
15.static boolean interrupted()
MULTITHREADING IN JAVA
OUTPUT
Importance of Multithreading
● Why Multithreading?
○ Enhanced Performance: Multithreading allows programs to perform multiple
tasks simultaneously, leading to better CPU utilization.
○ Increased Responsiveness: Programs remain responsive to user input while
executing background tasks (e.g., file downloads).
○ Real-Time Applications: Used in games, simulations, and real-time
processing where quick task switching is needed.
● Key Advantage: Concurrency allows for better management of computational
tasks in parallel.
MULTITHREADING IN JAVA
OUTPUT
OUTPUT
Number: 1
Message: Hello from the thread!
Number: 2
Number: 3
Message: Hello from the thread!
Number: 4
Number: 5
Message: Hello from the thread!
Message: Hello from the thread!
Message: Hello from the thread!
Both threads have finished execution.
MULTITHREADING IN JAVA
Thread Synchronization
Definition:
Thread Synchronization Thread synchronization is the concurrent execution of two or more
threads that share critical resources. When two or more threads need to use a shared resource, they
need some way to ensure that the resource will be used by only one thread at a time. The
process of ensuring single thread access to a shared resource at a time is called synchronization.
Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts
may arise when parallel-running threads attempt to modify a common variable at the same time.
OUTPUT
Thread-0 - Count: 1
Thread-0 - Count: 2
Thread-0 - Count: 3
Thread-0 - Count: 4
Thread-0 - Count: 5
Thread-1 - Count: 6
Thread-1 - Count: 7
Thread-1 - Count: 8
Thread-1 - Count: 9
Thread-1 - Count: 10
MULTITHREADING IN JAVA
https://www.youtube.com/watch?v=mTzqVinpU1E&ab_channel=CrioDo
MULTITHREADING IN JAVA
Thread States
● 1. New
○ Thread is created.
● 2. Runnable
○ Thread is ready to run.
● 3. Blocked
○ Thread is waiting for a resource.
● 4. Suspended
○ Thread is temporarily paused.
● 5. Terminated
○ Thread has finished execution.
MULTITHREADING IN JAVA
Suspending Threads
● Definition:
○ Temporarily halting a thread's execution.
● How to Suspend:
○ Use methods like suspend() (deprecated in some
languages).
● Use Cases:
○ Pausing for resource availability or user input.
MULTITHREADING IN JAVA
Resuming Threads
● Definition:
○ Restarting a suspended thread.
● How to Resume:
○ Use methods like resume().
● Considerations:
○ Ensure that the thread can safely continue
execution.
MULTITHREADING IN JAVA
Stopping Threads
● Definition:
○ Forcibly terminating a thread's execution.
● How to Stop:
○ Use methods like stop() (deprecated in some
languages).
● Risks:
○ Can lead to resource leaks or inconsistent state.
MULTITHREADING IN JAVA
OUTPUT
● In Java, wrapper classes are used to convert primitive data types (like
int, char, double, etc.) into corresponding objects.
Boxing or wrapping
MULTITHREADING IN JAVA
Boxing or wrapping
Boxing or wrapping
OUTPUT