5.0 Exception Handling & Robust Programming
5.1 Fundamentals of Exceptions
-
Definition: An exception is an event that disrupts the normal flow of a program. It is an object representing an error or unusual condition.
-
Error Types:
-
Compile-time (Syntax) Errors: Detected by the compiler (e.g., missing semicolon).
-
Runtime (Logical) Errors: Occur during execution; exceptions are used to handle these.
-
-
Exception Hierarchy:
| Class | Description | | :--- | :--- | |
Throwable| Root of all exceptions. | |Exception| Conditions a program might want to catch. | |RuntimeException| Unchecked exceptions (e.g.,NullPointerException). | |Error| Serious system errors (e.g.,OutOfMemoryError), not caught. | -
Checked vs. Unchecked Exceptions:
-
Checked: Subclasses of
Exception(excludingRuntimeException). Must be declared or handled (e.g.,IOException). -
Unchecked: Subclasses of
RuntimeExceptionorError. Handling is optional (e.g.,ArithmeticException).
-
5.2 Try-Catch Mechanism
-
Syntax:
try { // Code that might throw an exception } catch (ExceptionType1 e1) { // Handler for ExceptionType1 } catch (ExceptionType2 e2) { // Handler for ExceptionType2 } finally { // Code that ALWAYS executes (cleanup) } -
Multiple
catchBlocks: Order matters! Place more specific exceptions before general ones (e.g.,catch(FileNotFoundException)beforecatch(IOException)). Otherwise, the general catch will "catch" all, making specific ones unreachable → Compile Error. -
The
finallyBlock:-
Executes regardless of whether an exception was thrown or caught.
-
Used for critical cleanup (e.g., closing files, releasing resources).
-
Executes even if
tryorcatchcontains areturnstatement.
-
[!TIP] Common Pitfall: A
finallyblock will not execute if the JVM exits abruptly (e.g.,System.exit(), power failure, infinite loop).
5.3 Throwing Exceptions
-
throwStatement: Used to manually throw an exception object.if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } -
Custom Exceptions: Create by extending
Exception(for checked) orRuntimeException(for unchecked).class InsufficientFundsException extends Exception { public InsufficientFundsException(String msg) { super(msg); } }
5.4 The throws Clause
-
Purpose: Declares that a method might throw a listed exception. Forces the caller to handle or declare it.
public void readFile(String path) throws IOException { // Method body } -
throwvs.throws:-
throw: Action – throws an exception object. -
throws: Declaration – part of method signature, lists possible exceptions.
-
5.5 Common Exception Classes
| Exception | Typical Cause |
|---|---|
ArithmeticException |
Division by zero (/0). |
NullPointerException |
Accessing method/field on a null reference. |
ArrayIndexOutOfBoundsException |
Invalid array index. |
NumberFormatException |
Parsing invalid number string (e.g., Integer.parseInt("abc")). |
IOException |
General I/O failure (file not found, read error). |
5.1 Fundamental Java APIs & Strings (Deep Dive)
5.1.1 The String Class Revisited
-
Immutability: Once created, a
Stringobject's value cannot be changed. Operations likeconcat()orreplace()return newStringobjects.- Implication: Frequent modification (e.g., in loops) is inefficient → use
StringBuilder.
- Implication: Frequent modification (e.g., in loops) is inefficient → use
-
Essential Methods:
| Method | Purpose | Returns | | :--- | :--- | :--- | |
length()| Number of characters. |int| |charAt(i)| Character at indexi. |char| |substring(b, e)| Substring fromb(inclusive) toe(exclusive). |String| |equals(obj)| Content equality (case-sensitive). |boolean| |compareTo(str)| Lexicographical comparison. |int(<0, 0, >0) | |indexOf(ch)| First index of character/substring. |int(-1 if not found) | |toLowerCase(),toUpperCase()| Case conversion. |String| |trim()| Removes leading/trailing whitespace. |String| |split(regex)| Splits string into array using regex delimiter. |String[]| -
StringBuilder/StringBuffer:-
Mutable sequence of characters.
-
StringBuilder(non-synchronized, faster) vs.StringBuffer(synchronized, thread-safe). -
Key methods:
append(),insert(),delete(),reverse().
-
5.1.2 Wrapper Classes & Autoboxing/Auto-unboxing
-
Purpose: Represent primitive types as objects (e.g., for collections which require objects).
-
Key Wrappers:
Integer,Double,Character,Boolean. -
Conversion:
-
Primitive → Object (Boxing):
Integer i = 10;(Autoboxing) -
Object → Primitive (Unboxing):
int j = i;(Auto-unboxing) -
Explicit:
Integer i = Integer.valueOf(10);/int j = i.intValue();
-
-
Utility Methods:
Integer.parseInt(String),Double.parseDouble(String),String.valueOf(primitive).
5.2 Collections Framework (Introduction)
5.2.1 Core Interfaces & Purpose
| Interface | Order? | Duplicates? | Common Implementations | Key Feature |
|---|---|---|---|---|
List |
Yes (by index) | Yes | ArrayList, LinkedList |
Random access (get(i)). |
Set |
No | No | HashSet, LinkedHashSet |
Uniqueness. LinkedHashSet preserves insertion order. |
Map |
N/A (key-value) | Keys: No, Values: Yes | HashMap, LinkedHashMap |
Key-based lookup. LinkedHashMap preserves insertion order. |
5.2.2 Common Operations
-
Adding:
list.add(obj),map.put(key, value) -
Accessing:
list.get(index),map.get(key) -
Removing:
list.remove(index)orlist.remove(obj),map.remove(key) -
Iteration:
// Enhanced for-loop for (String s : list) { ... } // Iterator Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); } -
CollectionsUtility Class:-
Collections.sort(list) -
Collections.shuffle(list) -
Collections.binarySearch(list, key)(requires sorted list)
-
5.2.3 Generics (Introduction)
-
Purpose: Provide type safety at compile time. Eliminates need for casting and prevents
ClassCastExceptionat runtime. -
Syntax:
List<String> names = new ArrayList<>(); -
Raw Types vs. Parameterized Types:
-
Raw:
List list = new ArrayList();// Unsafe, generates warning. -
Parameterized:
List<String> list = new ArrayList<String>();// Safe.
-
-
Generic Class/Method:
class Box<T> { private T item; }
5.3 File I/O (Basic)
5.3.1 Streams, Readers, and Writers
-
Byte Streams (
InputStream/OutputStream): For raw binary data (images, audio). -
Character Streams (
Reader/Writer): For text data (handles character encoding). Preferred for text files. -
FileClass: Represents file/directory path names. Does not create/file data.File f = new File("test.txt"); boolean exists = f.exists();
5.3.2 Reading & Writing Text Files
| Class | Purpose | Buffering? |
|---|---|---|
FileReader / FileWriter |
Basic character stream. | No (inefficient for many small reads/writes). |
BufferedReader / BufferedWriter |
Wraps another reader/writer for efficiency (buffers data). | Yes |
PrintWriter |
Convenient print()/println() methods. Can wrap BufferedWriter. |
Optional |
-
Try-with-resources (Java 7+): Automatically closes resources (
AutoCloseable).try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } // br is automatically closed here.\boxed{\text{try (ResourceType res = new Resource()) { } catch (Exception e) { }}}
5.4 Introduction to Multithreading (Basic Concepts)
5.4.1 What is a Thread?
-
A thread is a lightweight sub-process, the smallest unit of execution.
-
Creating Threads:
-
Extend
Threadclass: Overriderun().class MyThread extends Thread { public void run() { /* task */ } } new MyThread().start(); -
Implement
Runnableinterface: PassRunnabletoThreadconstructor. Preferred (Java doesn't support multiple inheritance).class MyRunnable implements Runnable { public void run() { /* task */ } } new Thread(new MyRunnable()).start();
-
5.4.2 Thread Lifecycle & States
-
NEW: Thread object created,
start()not called. -
RUNNABLE: Thread is executing or ready to execute (in runnable pool).
-
BLOCKED: Waiting to acquire a monitor lock (for synchronized block/method).
-
WAITING: Waiting indefinitely (
Object.wait(),Thread.join()). -
TIMED_WAITING: Waiting for specified time (
Thread.sleep(ms)). -
TERMINATED:
run()completed or died.
5.4.3 Basic Thread Control
-
start():** *Starts* the thread and callsrun()**in a new call stack**. **Never callrun()` directly (executes in current thread). -
`run(): Contains the code to be executed in the new thread.
-
**
Thread.sleep(ms):** Pauses current thread formsmilliseconds. ThrowsInterruptedException`. -
synchronized: Keyword to prevent thread interference and memory consistency errors.-
Synchronized method:
public synchronized void method() { ... } -
Synchronized block:
synchronized(obj) { ... }
-
[!TIP] Exam Focus: Understand the difference between
start()(creates new thread) andrun()(ordinary method call). Know whysynchronizedis needed (shared mutable data).
5.5 Introduction to GUI Programming (Swing)
5.5.1 AWT vs. Swing
-
AWT: Heavyweight components (native OS peers).
java.awtpackage. -
Swing: Lightweight components (pure Java, more flexible).
javax.swingpackage.-
Pluggable Look-and-Feel (PLAF): Can change appearance at runtime.
-
All Swing components start with
J(e.g.,JFrame,JButton).
-
5.5.2 Core Swing Components
| Component | Purpose |
|---|---|
JFrame |
Top-level window (main application window). |
JDialog |
Pop-up window dependent on a frame. |
JLabel |
Display read-only text or image. |
JButton |
Clickable button. |
JTextField |
Single-line text input. |
JTextArea |
Multi-line text input. |
JCheckBox |
On/off toggle (multiple selections allowed). |
JRadioButton |
Mutually exclusive selection (used with ButtonGroup). |
-
Layout Managers: Control component arrangement.
-
FlowLayout(default forJPanel): Left-to-right, wraps. -
BorderLayout(default forJFramecontent pane): North, South, East, West, Center. -
GridLayout(rows, cols): Uniform grid.
-
5.5.3 Event Handling
-
Event Delegation Model:
-
Event Source: Component that generates event (e.g.,
JButton). -
Event Object: Encapsulates event info (e.g.,
ActionEvent). -
Listener Interface: Defines callback method (e.g.,
ActionListenerwithactionPerformed(ActionEvent e)). -
Listener Object: Class that implements listener interface and is registered with source.
-
-
Registering Listener:
button.addActionListener(listenerObject); -
Anonymous Inner Class (Common Pattern):
JButton btn = new JButton("Click"); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Code to execute on click } });Java 8+ Lambda:
btn.addActionListener(e -> { /* code */ });(sinceActionListeneris a Functional Interface).