Unit III: Exception Handling and Multithreading
Exception Handling
Exception Handling in Java
Definition:
Exception handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, etc.
Key Concepts:
1. Exception Hierarchy
2. Checked and Unchecked Exceptions
3. try, catch, throw, throws, finally
4. User Defined Exceptions
Syntax:
try {
// code that may throw exception
} catch(ExceptionType name) {
// code to handle the exception
} finally {
// code that will execute no matter what
Example:
public class TryCatchExample {
Unit III: Exception Handling and Multithreading
public static void main(String args[]) {
try {
int data = 100 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Finally block executed");
Multithreading
Multithreading in Java
Definition:
Multithreading is a process of executing multiple threads simultaneously. A thread is a lightweight
subprocess.
Key Topics:
1. Thread Life Cycle
2. Creating and Running Threads
3. Implementation Types: Extending Thread class / Implementing Runnable Interface
4. Thread Priorities
5. Thread Synchronization
Unit III: Exception Handling and Multithreading
6. Inter-thread Communication
Thread Life Cycle:
1. New
2. Runnable
3. Running
4. Waiting/Blocked
5. Terminated
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
public static void main(String args[]) {
MyThread t1 = new MyThread();
t1.start();
Synchronization Syntax:
synchronized void methodName() {
// synchronized code