Unit 3: Exception handling and multithreading
Java Technologies notes · PTU syllabus (PGCA1939)
On this page
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
- 1. New: Thread created
- 2. Runnable: start() called
- 3. Running: Scheduler picks it
- 4. Blocked or waiting: sleep(), wait(), I/O
- 5. Terminated: run() finishes
Topic 1
Types of errors and exceptions
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
Error
Serious problems — OutOfMemoryError, StackOverflowError; not handled
Checked exceptions
Checked at compile time — IOException, SQLException, FileNotFoundException
Unchecked (RuntimeException)
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException
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(); }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());
}- 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.
Topic 4
The Java thread model
- 1New
Created
- 2Runnable
start() called
- 3Running
Scheduled on CPU
- 4Blocked or waiting
sleep, wait, I/O, lock
- 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.
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).
Topic 6
Inter-thread communication
- 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.
Topic 7
Suspending, resuming and stopping threads
suspend(),resume()andstop()are deprecated (deadlock and inconsistent state). Use a volatile flag checked in run(),interrupt(),sleep()andjoin()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
- Q1.Distinguish checked and unchecked exceptions.
- Q2.What is the use of finally?
- Q3.Distinguish throw and throws.
- Q4.Name the states of a thread.
- Q5.What is synchronisation?
- Q6.Why is stop() deprecated?
Long-answer questions
- Q1.Explain exception handling in Java with an example.
- Q2.Explain the Java thread model and creating threads.
- 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.
