Top Banner Ad

BCS403 — Unit 2: Exception Handling

Table of Contents (14 sections)

BCS403 · Object Oriented Programming with Java · Unit 2

Exception Handling

Unit Scope & Exam Weightage: This unit covers the idea behind exceptions, errors vs. exceptions, checked and unchecked types, JVM reaction to exceptions, try/catch/finally/throw/throws, built-in and user-defined exceptions, byte and character streams with file reading/writing, and multithreading — thread life cycle, creation methods, priorities, synchronization and inter-thread communication. AKTU asks at least one 7-mark program (custom exception / threads / file I/O) and several 2-mark definition questions.


Importance-Wise Roadmap (BCS403 Unit 2)

Priority Exact Syllabus Topic PYQ Evidence Marks Pattern Tag
1 Threads: creation, even/odd, alternate printing, wait/notify 2023-24, 2024-25, 2025-26 7m × 4 + 2m Program heavy
2 try/catch/finally/throw/throws, checked vs unchecked 2023-24, 2024-25, 2025-26 7m + 2m × 4 Repeat clusters
3 Byte vs character streams and file I/O 2023-24, 2025-26 7m × 2 Comparison + code
4 User-defined exceptions (InvalidPasswordException) 2025-26 7m Code
5 Thread life cycle, priorities, synchronization 2023-24 2m + integrated Theory
6 Error vs Exception, control flow in exceptions Not directly asked Predicted Backup

Java-specific examiner guidance: For a program question, write the class with main, the exact try-catch-finally nesting (or synchronized/wait()/notify() placement), and the observed output. A custom exception must call super(message) and be thrown with throw new X(...).


1. Exception Handling Fundamentals

Exception: an abnormal event occurring during execution that disrupts the normal flow of instructions. Java represents it as an object of a class derived from Throwable. An Error (e.g., OutOfMemoryError, StackOverflowError) is a serious JVM-level problem that programs should not normally catch; an Exception (e.g., ArithmeticException, IOException) can be handled.

        Throwable
        /        \
    Exception    Error
    /      \
RuntimeException   checked exceptions
(Arithmetic,        (IOException,
 NullPointer,        ClassNotFoundException,
 IndexOutOfBounds)   SQLException)

1.1 The Five Keywords

PYQ (2023-24, 2 marks): "Describe all the keywords used for exception handling in Java." Predicted (2025-26, 2 marks): "List the five Exception Handling keywords. Can a try block exist without a catch or finally?"

Keyword Role
try Block of code that may raise an exception
catch Block that handles a matching exception type
finally Block always executed (cleanup), even on exception or return
throw Explicitly raises an exception object: throw new ...
throws Declares in a method signature that exceptions may propagate to the caller

Can a try exist alone? No. A try must be followed by at least one catch or a finally block (try-with-resources also includes a resource specification). try { ... } with neither is a compile-time error.

PYQ (2024-25, 2 marks): "What is the purpose of the finally block in Java exception handling?" It holds cleanup code (closing files, releasing resources) that must run whether or not an exception occurred; it executes even if catch returns, except when the JVM halts via System.exit().

PYQ (2024-25, 2 marks): "How is throw different from throws?" throw is a statement used inside a method to actually raise one exception object. throws is a clause in the method declaration listing exception classes that the method may pass to its caller. throw new IOException() vs. void read() throws IOException.

PYQ (2023-24, 7 marks): "Differentiate between checked and unchecked exceptions in Java. Write a Java program to demonstrate Arithmetic Exception handling."

Checked Unchecked
Subclasses of Exception excluding RuntimeException RuntimeException and its subclasses
Compiler forces handling/declaration Compiler does not force handling
Usually external conditions (file missing, DB down) Programming bugs (bad index, null reference)
IOException, SQLException, ClassNotFoundException ArithmeticException, NullPointerException, IndexOutOfBoundsException
public class ArithmeticDemo {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            System.out.println(a / b);      // division by zero
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } finally {
            System.out.println("Arithmetic demo finished");
        }
    }
}

Output:

Cannot divide by zero: / by zero
Arithmetic demo finished

Control flow: the statement that throws is abandoned → JVM searches for the nearest matching catch in the call stack → catch runs → finally runs → execution continues after the try/catch structure. If no catch matches, propagation continues up the call stack after finally executes.

Predicted (bank PRED, 2024-25, 7 marks): "Write a Java program to handle multiple exceptions using try-catch-finally." Use multi-catch catch (ArithmeticException | ArrayIndexOutOfBoundsException e) or ordered catch blocks (most specific first). Example: an array access and a division inside one try, two catches, one finally printing "cleanup".

1.2 User-Defined Exception

PYQ (2025-26, 7 marks): "Create a Custom Exception class named InvalidPasswordException. Write a program that throws this exception if a user's password is less than 8 characters long."

class InvalidPasswordException extends Exception {
    InvalidPasswordException(String msg) { super(msg); }
}

public class PasswordCheck {
    static void validate(String pwd) throws InvalidPasswordException {
        if (pwd.length() < 8)
            throw new InvalidPasswordException("Password must be at least 8 characters");
        System.out.println("Password accepted");
    }
    public static void main(String[] args) {
        try {
            validate("java");          // too short
        } catch (InvalidPasswordException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Validation complete");
        }
    }
}

Output:

Error: Password must be at least 8 characters
Validation complete

Extending Exception makes it checked, so validate declares throws. Extending RuntimeException would make it unchecked.


2. I/O Basics — Byte and Character Streams

PYQ (2025-26, 7 marks): "Explain the difference between Byte Streams and Character Streams. Describe the classes used to read and write a simple text file."

Byte streams Character streams
Handle 8-bit bytes Handle 16-bit Unicode characters
Base classes InputStream, OutputStream Base classes Reader, Writer
File classes FileInputStream, FileOutputStream File classes FileReader, FileWriter
Buffered wrappers BufferedInputStream, BufferedOutputStream Buffered wrappers BufferedReader, BufferedWriter
Use for binary data (images, .class, audio) Use for text with any script
No automatic encoding conversion Uses platform/default charset (or specify explicitly)

Reading/writing a text file:

import java.io.*;
public class FileCopy {
    public static void main(String[] args) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader("in.txt"));
             BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        }   // try-with-resources closes both streams automatically
        System.out.println("File copied");
    }
}

readLine() returns null at end of file. For byte-level work use FileInputStream.read() / FileOutputStream.write(int) in a loop.

PYQ (2023-24, 7 marks): "Differentiate between with suitable examples: 1. Character streams and Byte Streams 2. wait() and notify()"

wait() notify()
Called on the shared object inside synchronized Called on the same shared object inside synchronized
Current thread releases the lock and enters WAITING Wakes one waiting thread (no guarantee which)
Usually inside a while condition test notifyAll() wakes all waiting threads
Example: consumer waits when buffer is empty Example: producer notifies after adding an item

3. Multithreading

Thread (PYQ 2025-26, 2 marks): a lightweight unit of execution within a process; threads share the process's heap and code but have their own program counter, registers and stack. Multithreading allows concurrent execution of parts of a program, improving CPU utilization and responsiveness.

3.1 Thread Life Cycle

PYQ (2023-24, 2 marks): "Describe various states achieved by the thread in its life cycle."

State Meaning
New Thread object created, start() not yet called
Runnable / Ready start() called; waiting for CPU (includes Running in Java's model)
Running Executing its run() method
Blocked / Waiting / Timed waiting Waiting for lock (synchronized), wait(), sleep(ms) or join
Terminated / Dead run() completed or stopped

3.2 Ways to Create a Thread

PYQ (2023-24, 7 marks): "Describe the ways to create the threads in Java with suitable code. Also explain which method is more suitable to create threads."

// Method 1: extend Thread
class T1 extends Thread {
    public void run() { System.out.println("Thread-1 running"); }
}
// Method 2: implement Runnable (preferred)
class T2 implements Runnable {
    public void run() { System.out.println("Thread-2 running"); }
}
public class TwoWays {
    public static void main(String[] args) {
        new T1().start();
        new Thread(new T2()).start();
    }
}

Possible output: (order may vary)

Thread-1 running
Thread-2 running

Why Runnable is preferred: a class can implement many interfaces but extend only one class, so it keeps the class free to extend another; it also separates the task from the thread mechanism and allows the same task object to be run by several threads.

PYQ (2025-26, 2 marks): "What is the difference between extending Thread and implementing Runnable?" Extending Thread inherits thread behaviour but consumes the single inheritance slot; implementing Runnable only supplies run() and needs a Thread wrapper — reusable and flexible.

3.3 Even and Odd Threads

PYQ (2024-25, 7 marks): "Write a Java program that creates two threads — one to print even numbers and the other for odd numbers."

public class EvenOdd {
    public static void main(String[] args) {
        Thread even = new Thread(() -> {
            for (int i = 2; i <= 10; i += 2) System.out.println("Even: " + i);
        });
        Thread odd = new Thread(() -> {
            for (int i = 1; i <= 10; i += 2) System.out.println("Odd : " + i);
        });
        even.start();
        odd.start();
    }
}

Output (one possible interleaving):

Odd : 1
Even: 2
Odd : 3
Even: 4
...
Even: 10

Order can differ because the scheduler decides; even.join() after start() would force the odd thread to finish before subsequent statements.

PYQ (2024-25, 7 marks): "Explain the concept of multithreading. Write a program to implement two threads printing numbers alternatively." Use a shared lock and wait()/notifyAll() to alternate strictly:

class Alternate {
    static final Object lock = new Object();
    static boolean oddTurn = true;
    static void printOdd() throws InterruptedException {
        synchronized (lock) {
            for (int i = 1; i <= 5; i += 2) {
                while (!oddTurn) lock.wait();
                System.out.println("Odd : " + i);
                oddTurn = false;
                lock.notifyAll();
            }
        }
    }
    static void printEven() throws InterruptedException {
        synchronized (lock) {
            for (int i = 2; i <= 10; i += 2) {
                while (oddTurn) lock.wait();
                System.out.println("Even: " + i);
                oddTurn = true;
                lock.notifyAll();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> { try { printOdd(); } catch (InterruptedException e) { } });
        Thread t2 = new Thread(() -> { try { printEven(); } catch (InterruptedException e) { } });
        t1.start(); t2.start(); t1.join(); t2.join();
    }
}

Output (deterministic alternation):

Odd : 1
Even: 2
Odd : 3
Even: 4
Odd : 5
Even: 6
Odd : 7
Even: 8
Odd : 9
Even: 10

The while (not if) around wait() protects against spurious wakeups.

3.4 Synchronization and Priorities

synchronized on a method or block gives each object one lock; only one thread may hold it at a time. Thread.sleep(ms) pauses without releasing locks; wait() releases the lock; join() waits for another thread to die. Priorities range Thread.MIN_PRIORITY=1, NORM_PRIORITY=5, MAX_PRIORITY=10 — scheduling hints, not guarantees. Deadlock arises when two threads hold locks the other needs; avoid by consistent lock ordering.

3.5 Producer–Consumer with wait()/notify()

PYQ (2025-26, 7 marks): "Write a Java program to solve the Producer-Consumer problem using a shared buffer and methods - wait() and notify()."

class Buffer {
    private int item;
    private boolean empty = true;
    synchronized void put(int value) throws InterruptedException {
        while (!empty) wait();             // buffer full -> wait
        item = value;
        empty = false;
        notifyAll();                       // wake consumer
    }
    synchronized int get() throws InterruptedException {
        while (empty) wait();              // buffer empty -> wait
        empty = true;
        notifyAll();                       // wake producer
        return item;
    }
}
public class ProducerConsumer {
    public static void main(String[] args) {
        Buffer b = new Buffer();
        Thread p = new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                try { b.put(i); System.out.println("Produced " + i); }
                catch (InterruptedException e) { }
            }
        });
        Thread c = new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                try { System.out.println("Consumed " + b.get()); }
                catch (InterruptedException e) { }
            }
        });
        p.start(); c.start();
    }
}

Output:

Produced 1
Consumed 1
Produced 2
Consumed 2
Produced 3
Consumed 3

4. Exam-Ready Question Index and Practice

Question (source) Section
Five exception keywords (2023-24, 2m) §1.1
finally purpose (2024-25, 2m) §1.1
throw vs throws (2024-25, 2m) §1.1
Checked vs unchecked + ArithmeticException (2023-24, 7m) §1.1
InvalidPasswordException (2025-26, 7m) §1.2
Byte vs char streams + file I/O (2025-26, 7m) §2
wait()/notify() vs streams (2023-24, 7m) §2 + §3.5
Two thread creation ways (2023-24, 7m) §3.2
Even/odd threads (2024-25, 7m) §3.3
Alternate printing (2024-25, 7m) §3.3
Producer/Consumer (2025-26, 7m) §3.5
Thread lifecycle (2023-24, 2m) §3.1
Thread and Runnable (2025-26, 2m) §3.2

Practice questions (label: practice, not real PYQs)

  1. Practice: Write a program catching ArrayIndexOutOfBoundsException and printing the exception class name.
  2. Practice: Demonstrate that finally executes even when catch contains a return.
  3. Practice: Copy a binary file with FileInputStream/FileOutputStream using a byte buffer.
  4. Practice: Create three threads with different priorities and observe scheduling order.
  5. Practice: Modify the buffer to hold 3 items and use separate notFull/notEmpty conditions.

5. Last-Night Survival Checklist (Unit 2 only)

  1. Five keywords: try, catch, finally, throw, throws — with one-line meanings and a valid example of each.
  2. Exception tree: Throwable → Exception (checked vs RuntimeException) vs Error.
  3. Thread programs: even/odd, strict alternation with wait()/notifyAll(), producer/consumer with a shared buffer.
  4. Streams: InputStream/OutputStream for bytes, Reader/Writer for Unicode text; readLine() ends at null.
  5. Two creation ways: extends Thread vs implements Runnable; say why Runnable is preferred.

Final Java reminder: In thread programs, use while around wait() and call notifyAll() while holding the same lock; in exception programs, put cleanup in finally. These two details are frequent grading points.