oops unit 2
oops unit 2
An exception in Java is an event that disrupts the normal flow of the program's Exception handling in Java is an effective mechanism for managing runtime errors
execution. It's a way for the program to signal that something unexpected or erroneous to ensure the application’s regular flow is maintained. Some Common examples of
has occurred. When an exception occurs, the normal sequence of instructions is exceptions include ClassNotFoundException, IOException, SQLException,
interrupted, and the program attempts to find an appropriate handler to deal with the RemoteException, etc. By handling these exceptions, Java enables developers to
situation. create robust and fault-tolerant applications.
Output
Note: When an exception occurs and is not handled, the program terminates
abruptly and the code after it, will never execute. Error: Division by zero is not allowed!
Program continues after handling the exception.
Exception Handling in Java
Note: With the help of exception handling we can detect and handle the exceptions
gracefully so that the normal flow of the program can be maintained.
Note: The finally block always executes, even if no exception occurs, making it a
reliable place for cleanup operations.
The summary is depicted via visual aid below as follows:
Java Exception Handling is a mechanism to handle runtime errors, allowing a program finally {
to continue operating or terminate gracefully. It separates error-handling code from // cleanup code
regular code, enhancing readability and maintainability. Without proper exception }
handling, an error can cause the entire application to crash, leading to a poor user
experience.
Java provides a structured way to handle exceptions using five key keywords: try,
catch, finally, throw, and throws. throw new IOException("File not found");
1. try: The try block contains code that might throw an exception. If an exception
occurs within this block, the control is transferred to the corresponding catch block.
5. throws: The throws keyword is used in the method signature to declare that the
method might throw exceptions.
try {
// code that may throw an exception
} catch (ExceptionType e) { public void readFile() throws IOException {
// code to handle the exception // method code
} }
2. catch: The catch block is used to handle the exception thrown by the try block.
Multiple catch blocks can be used to handle different types of exceptions. 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
catch (IOException e) { exceptions if it occurs.
// handle IOException try {
} catch (SQLException e) { // Code that may throw an exception
// handle SQLException } catch (ExceptionType e) {
} // Code to handle the exception
}
finally Block
The finally Block is used to execute important code regardless of whether an
3. finally: The finally block contains code that will always execute, regardless of exception occurs or not.
whether an exception was thrown or not. It is typically used for cleanup activities, such Note: finally block is always executes after the try-catch block. It is also used for
as closing files or releasing resources. resource cleanup.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}finally{
// cleanup code
}
Let us see an example that illustrates how a run-time system searches for appropriate
exception handling code on the call stack.
Example:
// Class
// ExceptionThrown
class Gks {
// Try block to check for exceptions // This statement will never execute
// as above we caught with an exception Java throw
System.out.println("Hi, I want to execute"); The throw keyword in Java is used to explicitly throw an exception from a method
} or any block of code. We can throw either checked or unchecked exception. The
} throw keyword is mainly used to throw custom exceptions.
Syntax of Java throws Explanation: In the above program, by using the throws keyword we handled
type method_name(parameters) throws exception_list the InterruptedException and we will get the output as Hello Gks.
where, exception_list is a comma separated list of all the exceptions which a method
might throw. Example 3: Throwing an Exception with throws
In a program, if there is a chance of raising an exception then the compiler always class Gks {
warns us about it and compulsorily we should handle that checked exception,
Otherwise, we will get compile time error saying unreported exception XXX must static void fun() throws IllegalAccessException
be caught or declared to be thrown. To prevent this compile time error we can {
handle the exception in two ways: System.out.println("Inside fun(). ");
1. By using try catch throw new IllegalAccessException("demo");
1. By using the throws keyword }
We can use the throws keyword to delegate the responsibility of exception handling
to the caller (It may be a method or JVM) then the caller method is responsible to public static void main(String args[])
handle that exception. {
try {
Example 1: Unhandled Exception fun();
// Java program to illustrate error in case }
// of unhandled exception catch (IllegalAccessException e) {
class Gks { System.out.println("Caught in main.");
public static void main(String[] args) }
{ }
Thread.sleep(10000); }
System.out.println("Hello Gks");
} Output
Inside fun(). 3) System.err: standard error stream
Caught in main. Let's see the code to print output and an error message to the console.
Readers/Writers: Readers and writers are specialized stream classes designed for
handling character data. They provide a convenient way to read from and write to
character-based data sources. Readers read character data from input streams, while
writers write character data to output streams.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Byte streams offer a low-stage interface for studying and writing character bytes or
blocks of bytes. They are normally used for coping with non-textual statistics,
studying and writing files of their binary form, and running with network sockets.
Byte streams don't perform any individual encoding or deciphering. They treat the
data as a sequence of bytes and don't interpret it as characters.
These streams can be different in how they are handling data and the type of data they
are handling. Character Encoding Automatic encoding and No encoding or decoding
decoding
1. Character Streams:
Character streams are designed to address character based records, which includes
textual records inclusive of letters, digits, symbols, and other characters. These Text vs non-Text data Text-based data, strings Binary data, images, audio,
streams are represented by way of training that quit with the phrase "Reader" or video
"Writer" of their names, inclusive of FileReader, BufferedReader, FileWriter, and
BufferedWriter.
Performance Additional conversion may Efficient for handling large
Character streams offer a convenient manner to read and write textual content- impact performance binary data
primarily based information due to the fact they mechanically manage character
encoding and decoding. They convert the individual statistics to and from the
underlying byte circulation the usage of a particular individual encoding, such as
Handle Large Text Files May impact performance due to Efficient, no encoding overhea
UTF-eight or ASCII.It makes person streams suitable for operating with textual
content files, analyzing and writing strings, and processing human-readable statistics. encoding
2. Byte Streams:
Byte streams are designed to deal with raw binary data, which includes all kinds of String Operations Convenient methods for string Not specifically designed for
data, including characters, pictues, audio, and video. These streams are represented operations string operations
Convenience Methods Higher-level abstractions for Low-level interface for byte Constructors:
FileWriter(File file) – Constructs a FileWriter object given a File object.
text data data
FileWriter (File file, boolean append) – constructs a FileWriter object given a
File object.
FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with
Reading Line by Line Convenient methods for reading Byte-oriented, no built-in line a file descriptor.
lines reading methods FileWriter (String fileName) – constructs a FileWriter object given a file name.
FileWriter (String fileName, Boolean append) – Constructs a FileWriter object
given a file name with a Boolean indicating whether or not to append the data
File Handling Read/write text files Read/write binary files written.
Methods:
Network Communication Sending/receiving text data Sending/receiving binary data public void write (int c) throws IOException – Writes a single character.
public void write (char [] stir) throws IOException – Writes an array of
characters.
Handling Images/Audio/Video Not designed for handling Suitable for handling binary public void write(String str)throws IOException – Writes a string.
public void write(String str, int off, int len)throws IOException – Writes a
binary data directly multimedia data
portion of a string. Here off is offset from which to start writing characters and
len is the number of characters to write.
public void flush() throws IOException flushes the stream
Text Encoding Supports various character No specific text encoding
public void close() throws IOException flushes the stream first and then closes
encodings support the writer.
Reading and writing take place character by character, which increases the number
of I/O operations and affects the performance of the system.BufferedWriter can be
used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter
Multithreading in Java
Running Threads
Multithreading is a Java feature that allows the concurrent execution of two or more If the class extends the Thread class, the thread can be run by creating an instance of
parts of a program for maximum utilization of the CPU. Each part of such a program the class and call its start() method:
is called a thread. So, threads are lightweight processes within a process.
Extend Example
Main obj = new Main(); Example: When a thread tries to access a synchronized block or method, but
another thread already holds the lock.
Thread thread = new Thread(obj);
Use case: Multiple threads accessing a shared resource can only be obtained by
thread.start(); a single Thread, such as a database or a file.
System.out.println("This code is outside of the thread"); Terminated: A thread reaches the termination state because of the following reasons:
} o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
public void run() { unhandled exception or segmentation fault.
System.out.println("This code is running in a thread");
2. Runnable state
Example: After calling the start() method on a thread, it enters the runnable Priorities in Threads
state.
Priorities in Threads in Java is a concept where each thread has a priority in Priority of running thread: 1
layman’s language one can say every object has priority here which is represented Priority of running thread: 5
by numbers ranging from 1 to 10, Priority of running thread: 10
public static int Sets the Maximum Priority for the Thread. Synchronized Blocks in Java
MAX_PRIORITY (Priority: 10) Java provides a way to create threads and synchronise their tasks
using synchronized blocks.
A synchronized block in Java is synchronized on some object. Synchronized
blocks in Java are marked with the synchronized keyword. All synchronized blocks
class Test extends Thread{
synchronize on the same object and can only have one thread executed inside them
public void run(){
at a time. All other threads attempting to enter the synchronized block are blocked
System.out.println("Priority of running thread: " +
until the thread inside the synchronized block exits the block.
Thread.currentThread().getPriority());
}
} General Form of Synchronized Block
synchronized(sync_object)
public class ThreadPriorityExample { {
public static void main(String args[]){ // Access shared variables and other
//creating thread. // shared resources
Test thrd1 = new Test(); }
Test thrd2 = new Test(); This synchronization is implemented in Java with a concept called monitors or
Test thrd3 = new Test(); locks. Only one thread can own a monitor at a given time. When a thread acquires a
lock, it is said to have entered the monitor. All other threads attempting to enter the
//set thread priority. locked monitor will be suspended until the first thread exits the monitor.
thrd1.setPriority(Thread.MIN_PRIORITY);
thrd2.setPriority(Thread.NORM_PRIORITY); Types of Synchronization
thrd3.setPriority(Thread.MAX_PRIORITY); There are the following two types of synchronization:
Syntax:
Inter-thread Communication in Java
1. public final void notifyAll()
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other. Understanding the process of inter-thread communication
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.
The point to point explanation of the above diagram is as follows:
Method Description
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state
of the object.
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.