KEMBAR78
Topic 12 - Exception Handling and Threading in Java | PDF | Thread (Computing) | Method (Computer Programming)
0% found this document useful (0 votes)
2 views44 pages

Topic 12 - Exception Handling and Threading in Java

The document provides an overview of exception handling and threading in Java, explaining the concept of exceptions, their types, and the importance of handling them for program stability. It also covers the creation and management of threads, including synchronization and inter-thread communication. Key Java keywords related to exception handling, such as 'throw', 'throws', and 'finally', are discussed along with examples to illustrate their usage.

Uploaded by

kusaltharindu739
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 views44 pages

Topic 12 - Exception Handling and Threading in Java

The document provides an overview of exception handling and threading in Java, explaining the concept of exceptions, their types, and the importance of handling them for program stability. It also covers the creation and management of threads, including synchronization and inter-thread communication. Key Java keywords related to exception handling, such as 'throw', 'throws', and 'finally', are discussed along with examples to illustrate their usage.

Uploaded by

kusaltharindu739
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/ 44

ITC 1233 - OBJECT ORIENTED

PROGRAMMING
EXCEPTION HANDLING AND THREADING IN JAVA

Ms.Nirasha Kulasooriya,
Lecturer, Dept. of ICT, FOT,USJ.
DO YOU KNOW WHAT IS AN EXCEPTION?
WHAT IS AN EXCEPTION?
An exception is an event that disrupts the normal flow of a
program's instructions during runtime. It is an abnormal condition
or error that occurs during the execution of a program.
KEY CHARACTERISTICS
• Unforeseen Circumstances:
Exceptions are often caused by unexpected events, such
as invalid user input, network issues, or file not found.
• Disruption of Normal Flow:
When an exception occurs, the normal flow of the
program is disrupted. Without proper handling, it could
lead to the termination of the program.
WHEN WE WERE MET AN EXCEPTION…
EXAMPLE SCENARIO
WHY EXCEPTION HANDLING
• Graceful Degradation: Allows the program to handle errors gracefully,
providing a mechanism to respond to unexpected situations without crashing.

• User Experience: Enhances the overall user experience by preventing abrupt


program termination and providing meaningful error messages.

• Resource Cleanup: Exception handling ensures that resources are properly


released, preventing resource leaks even in the presence of errors.

• Robustness: Enhances the robustness of the code, making it capable of


handling unexpected situations and continuing execution.
EXCEPTION DETECTION
JAVA EXCEPTION HIERARCHY
THROWABLE CLASS HIERARCHY
Exception handling in Java revolves around the Throwable class hierarchy,
which is divided into two main branches: Error and Exception.

1. java.lang.Throwable - At the top of the hierarchy. Acts as the base class for all exceptions
and errors.

2. java.lang.Error - Represents serious errors that are generally beyond the control of the
application. Examples include OutOfMemoryError and StackOverflowError. Typically, not
recoverable during runtime.

3. java.lang.Exception - Represents exceptions that can be caught and handled.


CHECKED EXCEPTIONS
Checked exceptions are exceptions that are checked at
compile time. The compiler ensures that these exceptions are
either handled by the programmer or declared in the method
signature using the throws keyword.
Ex: IOException: Thrown for input/output errors, such as file not found or read/write errors.

SQLException: Raised for database-related errors, like invalid SQL queries or connection issues.

ClassNotFoundException: Occurs when trying to load a class at runtime that is not found.

FileNotFoundException: Indicates that a file specified for input/output is not found.


UNCHECKED EXCEPTIONS
Unchecked exceptions are exceptions that are not checked at
compile time. These exceptions typically result from programming
errors and are subclasses of the RuntimeException class.

Ex: NullPointerException: Thrown when attempting to access an object that is null.

ArrayIndexOutOfBoundsException: Raised when attempting to access an array element with


an invalid index.

ArithmeticException: Occurs when an arithmetic operation is attempted with inappropriate


operands, such as division by zero.

IllegalArgumentException: Thrown when a method is passed an illegal or inappropriate


argument.
UNCAUGHT EXCEPTIONS
When an exception is thrown in Java and not caught or handled by the
program, it becomes an uncaught exception. Uncaught exceptions can
have several consequences, impacting the normal execution and behavior
of a Java program.

There are three (03) main ways:

1. Program termination

2. Resource leaks

3. Incomplete tasks
1. PROGRAM TERMINATION
Uncaught exceptions often lead to the termination of the
program. When an exception occurs and is not caught by an
appropriate catch block, it propagates up the call stack. If it
reaches the top level of the stack without being caught, the
Java Virtual Machine (JVM) terminates the program.
2. RESOURCE LEAKS
In situations where resources like files, sockets, or database
connections are not properly closed or released due to
uncaught exceptions, resource leaks can occur. Failing to
handle exceptions and release resources can lead to inefficient
resource utilization and, in some cases, impact the stability of the
system.
EXAMPLE
public class ResourceLeakExample {
public static void main(String[] args) {
// Uncaught exception leading to resource
leak
FileInputStream fileInputStream = new
FileInputStream("example.txt");
// Code that may throw an exception
// Resource is not closed in a finally block
}
}
3. INCOMPLETE TASKS
Uncaught exceptions may result in incomplete or inconsistent
tasks. If an exception occurs during the execution of a critical
task, it might leave the program in an unpredictable state.
Incomplete tasks can lead to data corruption or incorrect
program behavior.
EXAMPLE
UNCAUGHT EXCEPTIONS
Handling exceptions through appropriate try-catch blocks, logging,
and graceful degradation of functionality is crucial to mitigate the
consequences of uncaught exceptions and ensure the stability and
reliability of Java applications.
USING TRY AND CATCH
In Java, the try and catch blocks are used to handle exceptions.
The try block encloses the code that may throw an exception,
and the catch block contains the code that handles the
exception if it occurs. Here's a basic structure of using try and
catch:
EXAMPLE: USING TRY AND CATCH
In Java, the try and catch blocks are used to handle exceptions.
The try block encloses the code that may throw an exception,
and the catch block contains the code that handles the
exception if it occurs. Here's a basic structure of using try and
catch:
EXAMPLE
In this example, the
divideNumbers method is
called within the try block.
If an ArithmeticException
occurs (e.g., division by
zero), the control is
transferred to the catch
block where the exception
is handled. The finally block
is optional but is often used
to ensure that certain code
executes, whether an
exception occurred or not.
KEY AREAS OF TRY-CATCH BLOCK
• Try Block:
Encloses the code that may throw an exception.
Only one try block can be associated with zero or more catch blocks.
• Catch Block:
Contains the code that handles a specific type of exception.
Multiple catch blocks can follow a single try block, each handling a
different type of exception.
• Finally Block:
Optional and follows the try and catch blocks.
Contains code that is guaranteed to execute, whether an exception
occurred or not.
MULTIPLE CATCH CLAUSES
• In Java, you can use multiple catch clauses to handle
different types of exceptions that may be thrown within a
single try block. This allows you to provide specific handling
mechanisms for various types of exceptions.

• This approach allows you to provide specialized handling for


different types of exceptions and ensures that your program
can respond appropriately to various error scenarios.
EXAMPLE
KEYWORDS IN EXCEPTION HANDLING
1. throw keyword
The throw keyword in Java is used to explicitly throw an exception. It is followed
by an instance of an exception or an expression that results in an exception.
This allows you to create and throw your own exceptions or propagate existing
ones.
Ex: public class ThrowExample {
public static void main(String[] args) {
try {
throw new IllegalArgumentException("This is
a custom exception");
} catch (IllegalArgumentException e) {
System.err.println("Caught exception: " +
e.getMessage());
}}}
KEYWORDS IN EXCEPTION HANDLING
2. throws clause
The throws keyword is used in the method signature to declare
that a method might throw one or more specified exceptions.
When a method is declared with the throws keyword, it indicates
that the responsibility for handling these exceptions lies with the
method's caller or the calling method.
EXAMPLE
KEYWORDS IN EXCEPTION HANDLING
3. Finally keyword
The finally keyword in Java is used to define a block of code that
will be executed regardless of whether an exception is thrown or
not. The finally block is often used for cleanup operations, such
as closing files or releasing resources, ensuring that these
operations occur even if an exception occurs.
EXAMPLE
DO YOU KNOW THREADS?
WHAT IS A THREAD?
• A thread is the smallest unit of execution within a process.

• Allows multiple tasks to run concurrently, providing


parallelism.
THREAD LIFE CYCLE
CREATING THREADS
• Extending thread class
class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}

MyThread myThread = new MyThread();


myThread.start();
CREATING THREADS
• Implementing Runnable Interface
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}

Thread myThread = new Thread(new MyRunnable());


myThread.start();
CREATING MULTIPLE THREADS
• Running multiple threads concurrently.
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

thread1.start();
thread2.start();
THREAD PRIORITIES
• Threads can be assigned priorities to influence their
execution order.
• Priorities range from Thread.MIN_PRIORITY to
Thread.MAX_PRIORITY (1 to 10).
Ex: myThread.setPriority(Thread.MAX_PRIORITY);
WHY DO WE USE SYNCHRONIZATION ?
• Prevents data corruption in multithreaded environments.

• Ensures that only one thread can access a critical section of


code at a time.
SYNCHRONIZED METHODS
public synchronized void mySynchronizedMethod() {
// Code that needs to be executed atomically
}
SYNCHRONIZED BLOCKS
public void myMethod() {
// Non-critical section

synchronized (lockObject) {
// Critical section
}

// Non-critical section
}
INTER THREAD COMMUNICATION
• Wait and Notify Mechanism:
Threads can communicate and coordinate their actions
using wait(), notify(), and notifyAll() methods.
EXAMPLE: INTER THREAD COMMUNICATION
// Thread 1
synchronized (sharedObject) {
while (conditionNotMet) {
sharedObject.wait();
}
// Code to be executed when the condition is met
}
// Thread 2
synchronized (sharedObject) {
// Code that changes the condition
sharedObject.notify();
}
ANY QUESTIONS?

You might also like