Module 3: Java Exception Handling and Multithreading – Revision Notes
1. Exception Handling in Java
Exceptions are errors that occur during runtime and disrupt program flow.
Java provides try-catch-finally blocks to handle them.
Why Needed:
Prevent program crash
Graceful recovery from errors
Maintain normal flow
Helpful for debugging and robustness
Basic Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Cleanup code here");
}
2. Exception Class Hierarchy
Throwable
/ \
Exception Error
/ \
Checked RuntimeException
Exceptions (Unchecked)
Checked: IOException, SQLException (must handle)
Unchecked: ArithmeticException, NullPointerException (optional handling)
Error: JVM-level issues like OutOfMemoryError
3. Types of Exceptions + Keywords
Types:
Checked: FileNotFoundException, IOException
Unchecked: ArithmeticException, NullPointerException
Keywords:
try, catch, finally, throw, throws
Sample Code:
try {
checkAge(16);
} catch (ArithmeticException e) {
System.out.println(e);
}
static void checkAge(int age) throws ArithmeticException {
if (age < 18) throw new ArithmeticException("Not eligible");
}
4. Common Exceptions
ArithmeticException - divide by 0
NullPointerException - access null object
ArrayIndexOutOfBoundsException - invalid index
NumberFormatException - invalid number string
FileNotFoundException - file does not exist
5. Built-in Exceptions
Type Examples
Checked IOException, SQLException
Unchecked NullPointer, ArithmeticException
Error StackOverflowError, OutOfMemory
Use try-catch to handle, and throws to declare.
6. Need for Multithreading
Allows parallel task execution
Efficient CPU usage
Useful in games, UI, real-time apps
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
7. Thread Life Cycle
States: New Runnable Running Waiting/Blocked Terminated
Diagram:
New
|
start()
|
Runnable
|
Running
|
sleep(), wait()
|
Terminated
Methods:
start(), run(), sleep(), join(), yield(), wait()
8. Thread Priority and Synchronization
Priorities range from 1 to 10
Set using setPriority(int)
Synchronization:
Prevents race conditions
Use synchronized keyword on method/block
Example:
synchronized void increment() {
count++;
}
9. Ways to Create Threads
1.
Extend Thread class
class A extends Thread { public void run() {...} }
2.
Implement Runnable
class B implements Runnable { public void run() {...} }
3.
Using Lambda Expression
Thread t = new Thread(() -> { ... });
Final Tips
Practice try-catch, synchronized, and start() usage
Draw diagrams (Thread life cycle)
Know the differences between Checked vs Unchecked exceptions
Know all 3 ways to create threads