Unit 3 of 4 · M.Sc IT Sem 4

Unit 3: Exception handling and multithreading

Java Technologies notes · PTU syllabus (PGCA1939)

3 min read7 topics9 exam questions
On this page
  1. Unit summary
  2. Types of errors and exceptions
  3. try, catch, finally and multiple catch
  4. Nested try and the throw statement
  5. The Java thread model
  6. Synchronisation
  7. Inter-thread communication
  8. Suspending, resuming and stopping threads
  9. Key terms
  10. Quick revision
  11. Important questions

Unit summary

Robust programs handle errors gracefully and use threads to do several things at once. This unit covers try, catch and finally, multiple and nested catch, throw, built-in exceptions, the Java thread model, priorities, synchronisation, inter-thread communication and controlling threads.

After this unit you can

  • Handle exceptions with try, catch, finally and throw
  • Identify built-in exceptions
  • Create threads and set priorities
  • Synchronise threads and use wait and notify

PTU syllabus topics

  • Try/catch/finally blocks
  • multiple and nested catch
  • throw statement
  • built-in exceptions
  • the Java thread model
  • thread priorities
  • synchronization
  • inter-thread communication
  • suspending/resuming/stopping threads
CycleJava thread life cycle
Java thread life cycle
1New
2Runnable
3Running
4Blocked or waiting
5Terminated
  1. 1. New: Thread created
  2. 2. Runnable: start() called
  3. 3. Running: Scheduler picks it
  4. 4. Blocked or waiting: sleep(), wait(), I/O
  5. 5. Terminated: run() finishes
1

Topic 1

Types of errors and exceptions

ComparisonCompile-time and run-time errors
Compile-time errors
Run-time errors

Detected by

javac

JVM while running

Examples

Missing semicolon, undeclared variable, type mismatch

Division by zero, array index out of bounds, null reference

Result

No .class file produced

Exception thrown; program stops if unhandled

ClassificationException hierarchy
Throwable
  • Error

    Serious problems — OutOfMemoryError, StackOverflowError; not handled

  • Checked exceptions

    Checked at compile time — IOException, SQLException, FileNotFoundException

  • Unchecked (RuntimeException)

    ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

2

Topic 2

try, catch, finally and multiple catch

javatry {
    int[] a = new int[3];
    int x = Integer.parseInt("12a");     // NumberFormatException
    a[5] = 10 / 0;
} catch (ArithmeticException | NumberFormatException e) {   // multi-catch
    System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
    System.out.println("Other error");
} finally {
    System.out.println("Always runs — close files here");
}

try (java.io.FileReader fr = new java.io.FileReader("a.txt")) {   // try-with-resources
    System.out.println((char) fr.read());
} catch (java.io.IOException e) { e.printStackTrace(); }
3

Topic 3

Nested try and the throw statement

javatry {
    try { int[] a = new int[2]; a[5] = 1; }
    catch (ArrayIndexOutOfBoundsException e) { System.out.println("inner"); }
    throw new IllegalStateException("custom");
} catch (IllegalStateException e) {
    System.out.println("outer: " + e.getMessage());
}
Key termsBuilt-in exceptions
ArithmeticException
Divide by zero
NullPointerException
Using a null reference
ArrayIndexOutOfBoundsException
Bad index
NumberFormatException
Invalid number string
ClassCastException
Bad cast
IOException (checked)
I/O failure
SQLException (checked)
Database error
  • Checked exceptions must be caught or declared with throws; unchecked (RuntimeException) need not.
4

Topic 4

The Java thread model

ProcessThread life cycle
  1. 1New

    Created

  2. 2Runnable

    start() called

  3. 3Running

    Scheduled on CPU

  4. 4Blocked or waiting

    sleep, wait, I/O, lock

  5. 5Terminated

    run() completes

javaclass Task implements Runnable {
    public void run() { for (int i = 1; i <= 3; i++) System.out.println(Thread.currentThread().getName() + " " + i); }
}
Thread t1 = new Thread(new Task(), "A"), t2 = new Thread(new Task(), "B");
t1.setPriority(Thread.MAX_PRIORITY);   // 10; MIN 1, NORM 5
t1.start(); t2.start();
  • Threads can be created by extending Thread or implementing Runnable (preferred); priorities are hints to the scheduler.
5

Topic 5

Synchronisation

javaclass Counter {
    private int c = 0;
    synchronized void inc() { c++; }   // one thread at a time
}
  • Without synchronisation, two threads updating shared data cause a race condition. A synchronized method or block acquires the object's monitor (lock).
6

Topic 6

Inter-thread communication

Key termsMethods (Object class)
wait()
Release the lock and wait until notified
notify()
Wake one waiting thread
notifyAll()
Wake all waiting threads
  • Classic use: producer–consumer — producer waits when the buffer is full; consumer waits when empty.
7

Topic 7

Suspending, resuming and stopping threads

  • suspend(), resume() and stop() are deprecated (deadlock and inconsistent state). Use a volatile flag checked in run(), interrupt(), sleep() and join() instead.
javavolatile boolean running = true;
public void run() { while (running) { /* work */ } }

Key terms

Checked exception
Must be caught or declared
throw
Statement that raises an exception
Race condition
Error from unsynchronised shared access
Monitor
Lock associated with every object
wait/notify
Methods for inter-thread communication

Quick revision

  • try, catch, finally; multiple and nested catch; throw and throws; built-in exceptions.
  • Thread life cycle; Thread vs Runnable; priorities.
  • synchronized; wait, notify; deprecated suspend/resume/stop.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.Distinguish checked and unchecked exceptions.
  2. Q2.What is the use of finally?
  3. Q3.Distinguish throw and throws.
  4. Q4.Name the states of a thread.
  5. Q5.What is synchronisation?
  6. Q6.Why is stop() deprecated?

Long-answer questions

  1. Q1.Explain exception handling in Java with an example.
  2. Q2.Explain the Java thread model and creating threads.
  3. Q3.Explain synchronisation and inter-thread communication.

Stuck on this unit?

Message SBS on WhatsApp for help with Java Technologies, or to ask about studying M.Sc IT at Synetic.

WhatsApp us