INTELLIGENCE LEARNING
BCS403 Object Oriented
Programming with Java
UNIT 2 ONE SHOT
INTELLIGENCE LEARNING
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
SYLLABUS
Unit 2
Exception Handling: The Idea behind Exception, Exceptions & Errors,
Types of Exception, Control Flow in Exceptions, JVM Reaction to
Exceptions, Use of try, catch, finally, throw, throws in Exception
Handling, In-built and User Defined Exceptions, Checked and Un-
Checked Exceptions.
Input /Output Basics: Byte Streams and Character Streams, Reading and
Writing File in Java.
Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread
Priorities, Synchronizing Threads, Inter-thread Communication.
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Exception Handling
Exception Handling is the way Java handles errors during program execution,
so your program doesn’t crash suddenly and can respond properly.
The Idea Behind Exception Handling:
Sometimes, things go wrong while your program runs (like dividing by 0, file
not found, etc.). These problems are called exceptions. Java gives you tools
(like try, catch) to handle these exceptions safely. Instead of crashing, your
program can show a friendly message or take another action.
Exception vs Error
Term Meaning Can We Handle?
A problem that happens while the
Exception program is running (like wrong Yes
input, missing file).
A serious problem that usually
Error comes from the system or memory No
(like system crash).
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Example of Exceptions:
Arithmetic Exception → divide by 0
Null Pointer Exception → using something that is not assigned
Array Index Out Of Bounds Exception → accessing wrong array index
Example of Errors:
Out Of Memory Error → not enough memory
Stack Overflow Error → too much recursion
Types of Exception
1. Checked Exceptions (Known at compile time (before program runs))
These are checked by the compiler. If not handled, your code will show an
error while compiling. You must handle these using try-catch or throws.
Examples:
IOException → file not found or can’t be read
SQLException → database issues
ClassNotFoundException → class not found in program
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
2. Unchecked Exceptions
These are not checked by the compiler. You get the error only when the
program runs. You may handle them, but it’s not required.
Examples:
ArithmeticException → divide by zero
NullPointerException → using null value
ArrayIndexOutOfBoundsException → accessing wrong array index
3. Inbuilt Exceptions (Predefined by Java)
These are already provided by Java. You can use them directly.
Examples:
ArithmeticException → divide by 0
NullPointerException → using null value
4. User-Defined Exceptions (Created by You)
These are exceptions that you create yourself, when you want to show a
custom error message for special situations.
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Control Flow in Exception Handling
Control Flow means:
“What part of your program runs next when an error happens.”
Java uses blocks like try, catch, and finally to handle these situations safely.
JVM Reaction to Exceptions (Java Virtual Machine)
JVM is the engine that runs Java programs.
Let’s see how it reacts when an exception comes:
Step-by-Step:
• JVM runs the try block
• If everything is fine, nothing special happens.
• If an exception happens:
• JVM searches for a matching catch block
• If found → it runs the catch block.
• If not found → JVM throws the exception to the caller method.
• If the exception is never caught, JVM:
• Prints an error message
• Stops the program (crash)
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
1. try Block – "Try this, it might fail"
They can used to write code that might cause an error. This is the first step in
exception handling. If error happens inside try block, Java jumps to catch block.
Explanation:
1. Java runs the code inside the try block.
2. If an error happens, it will go to the matching catch block and run that code.
3. If no error happens, then Java skips the catch block.
4. After that, if there is a finally block, it will always run, no matter what.
2. catch Block – "I'll catch the error"
This block runs only if error happens in try. You can write a message or take action
here. You can catch specific types of errors like ArithmeticException,
NullPointerException, etc. You can have multiple catch blocks to handle different types
of exceptions.
Explanation:
1. When an error (exception) happens in the try block.
2. Java will look for the first catch block that matches the type of that error.
3. That one matching catch block will run.
4. All other catch blocks will be skipped (ignored).
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
3. finally Block – "I’ll always run"
Always runs, whether there was an error or not. Used for cleanup work like closing
files, connections, etc. Can be used with or without catch.
Explanation:
The finally block is always run, no matter what happens —
➤ If error comes → it runs
➤ If no error → it still runs
It is used to do cleanup work like:
Closing files
Freeing memory
Resetting values
Disconnecting from the internet/database
Example:-
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Error happened");
} finally {
System.out.println("This will always run");
}
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
public class TryCatchFinallyExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException: " + e.getMessage());
} finally {
System.out.println("This will always be executed.");
}
System.out.println("Program continues...");
}
public static int divide(int a, int b) { OUTPUT DISPLAY:
return a / b; Caught an ArithmeticException: / by zero
} This will always be executed.
} Program continues...
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
4. throw – "Manually throw an error"
You use throw when you want to create your own error. You can throw built-in or
custom exceptions.
Explanation:
1. throw is used to throw an exception (error) manually in the code.
2. You use it when you find a special error condition (like wrong input).
3. When throw runs:
• The method stops working immediately.
• Java looks for a nearby try-catch block to handle the error.
4. If there is no try-catch, the program will stop (crash).
Syntax:
throw new ExceptionType("Error message");
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
5. throws – "This method might throw an error"
Used in method declaration to warn that this method may throw an exception.
Needed when you use methods like file reading, database, etc.
Explanation:
1. throws is used to declare that a method can throw an exception.
2. It is used mostly for checked exceptions (errors that Java checks at compile time).
3. The method that calls this method must either:
• Handle the exception using try-catch, or
• Declare it using throws too.
4. You can mention more than one exception using commas.
Syntax:
returnType methodName(parameters) throws ExceptionType1,
ExceptionType2 { // Method body}
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Java Input / Output (I/O) Basics
Java provides I/O classes to handle input (reading) and output (writing) operations
such as reading/writing files, data from the keyboard, or printing to the screen.
Byte Stream
Byte streams are used to read and write binary data. They handle raw bytes (0s and
1s), so they are best for: Images, Audio files, Video files, PDF/Excel files, Any non-text
files.
Input Stream (for Reading Bytes)
It is the base class for reading data (input) in byte format. You can read one byte at a
time using .read() method.
Common Classes:
FileInputStream – reads bytes from a file
BufferedInputStream – reads data using buffer (faster)
OutputStream (for Writing Bytes)
It is the base class for writing data (output) in byte format. You can write one byte at a
time using .write() method.
Classes:
FileOutputStream – writes bytes to a file
BufferedOutputStream – faster output using buffer
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Example of Input Stream (for Reading Bytes)
FileInputStream in = new FileInputStream("file.jpg");
int data;
while ((data = in.read()) != -1) {
System.out.print((char) data);
}
in.close();
Example of Output Stream (for Writing Bytes)
FileOutputStream out = new FileOutputStream("output.jpg");
out.write(65); // writes byte value 65 (which is 'A')
out.close();
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
What is Character Stream?
Character streams are used to read and write text (characters). They handle data as characters,
not as raw bytes. Used for text files (.txt) or any file with characters (letters, numbers, symbols).
1. File Reader (for Reading Characters)
File Reader is used to read data (text) from a file. It reads one character at a time. It is a subclass
of Reader.
Syntax:- FileReader in = new FileReader("path_to_file");
Ex:- FileReader reader = new FileReader("filename.txt");
int data;
while ((data = reader.read()) != -1) {
// process character}
reader.close();
2. File Writer (for Writing Characters)
File Writer is used to write characters (text) to a file. It writes one character at a time. It is a
subclass of Writer.
Synatx:- FileWriter in = new FileWriter("path_to_file");
Ex:- FileWriter writer = new FileWriter("filename.txt");
writer.write("Your text here");
writer.close();
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Multithreading in Java
Multithreading means running multiple tasks (threads) at the same time. A
Thread is the smallest unit of a process that runs independently. In Java, we
can create multiple threads to perform different tasks at the same time, which
makes the program faster and more efficient.
Benefits of Multithreading:
1. Faster Execution – Tasks can run at the same time.
2. Efficient CPU use – CPU stays busy with other threads while one waits.
3. Improves performance – Especially useful in games, servers, and large
programs.
4. Better user experience – UI stays responsive (e.g., download continues
while typing).
What is a Thread?
A Thread is a small part of a program that runs independently. In Java, a thread
is like a mini-program inside your main program. You use threads to do
multiple tasks at the same time (this is called multithreading).
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Thread Life Cycle in Java
A thread in Java goes through several stages during its life. This is called the Thread Life Cycle.
Here are the main stages:
1. New (Created)
This is the first stage. The thread is created, but it is not started yet. The thread is just an
object in memory.
2. Runnable
The thread is ready to run and waiting for the CPU. It may start running anytime, depending
on the CPU’s availability. It means the thread is active but not yet running.
3. Running
The thread is currently executing its task. The CPU gives time to this thread, so it runs its
code. Only one thread can run on a single CPU core at a time.
4. Blocked/Waiting
Sometimes, a thread needs to pause or wait for something (like a resource or another
thread). In this state, the thread is not doing any work. It will move back to the Runnable
state after the waiting is over.
5. Terminated (Dead)
The thread has finished its work or was stopped. It cannot be started again. The life of the
thread is over.
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Creating Threads in Java
1. By Extending the Thread Class
Steps:
1. In this method, you Create a new class that extends Thread
2. Override the run() method
3. Create object of the class and call start()
Important:
start() starts a new thread and calls run()
2. By Implementing the Runnable Interface
Steps:
1. Create a class that implements Runnable
2. Override the run() method
3. Pass object of this class to Thread class
4. Call start() on Thread object
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Thread Priority?
In Java, when you create multiple threads, the system (JVM + OS) needs
to decide which thread to run first. To help with this, each thread is
given a priority – a number from 1 to 10.
Thread Priority tells the JVM how important a thread is.
Priority Levels in Java:
Java provides 3 predefined constants:
Constant Value Meaning
Thread.MIN_PRIORITY 1 Lowest priority
Thread.NORM_PRIORITY 5 Normal/default priority
Thread.MAX_PRIORITY 10 Highest priority
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
Thread Synchronization
When two or more threads try to access the same data (or resource) at the same
time, it can cause conflicts or wrong results. To prevent this, Java provides
Synchronization. Synchronization means allowing only one thread at a time to access
the shared resource.
Why Synchronization is Needed
Imagine two people writing on the same notebook at the same time the writing will
be mixed and confusing.
If multiple threads read/write the same variable together, it may cause errors or data
corruption.
To avoid this, Java locks the object so that only one thread can use it at a time.
Types of Synchronization
1. Synchronized Method
The entire method is locked. Only one thread can call the method at a time.
2. Synchronized Block
Only a specific part of the code is locked (not the whole method). More efficient if
only a small part of the method needs protection.
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
What is Inter-thread Communication?
Inter-thread communication means that threads can talk to each other
and work together using special methods. Java gives us tools so that:
One thread can pause so, Another thread can wake it up
Why is it needed?
One thread is producing items
Another thread is using those items
They need to coordinate
This is where inter-thread communication helps!
Methods used
Method What it does
wait() Stops the thread and waits
notify() Wakes up one waiting thread
notifyAll() Wakes up all waiting threads
LIKE, SHARE, COMMENT & SUBSCRIBE
INTELLIGENCE LEARNING
THANK YOU FOR WATCHING
DO LIKE SHARE COMMENT AND SUBSCRIBE
LIKE, SHARE, COMMENT & SUBSCRIBE