Exception Handling
- Exception: A problem requiring immediate attention to resolve, without which the program cannot continue.
- Exceptions in Java: Objects thrown upon problem detection, needing to be caught to prevent program crashes.
- Refer to: https://docs.oracle.com/javase/tutorial/essential/exceptions/
- As Koenig & Stroustrup stated in “Exception Handling for C++,” 1989:
- Library authors can detect errors but may not know how to handle them.
- Library users might know how to cope with errors but cannot detect them.
- Koenig & Stroustrup (1989) describe exception handling as a mechanism for one part of a program to inform another about detected exceptional circumstances.
- Exceptional Control Flow:
- Exception thrown when a problem is detected.
- Exceptions are caught using try-catch blocks.
- Execution stack unwinds to find a handler.
Try-Catch
- Basic structure:
java
try {
// risky code
} catch (Exception e) {
// respond to exception
}
Kinds of Exceptions in Java
- Unchecked exceptions (aka errors):
- The compiler does not enforce handling.
- Generally indicate severe issues that crash the program.
- Examples:
OutOfMemoryError
, StackOverflowError
, NullPointerException
- Checked exceptions:
- Methods must declare any checked exceptions they might throw.
- Common in file IO or network interactions.
- All exceptions in Java are organized via inheritance.
Exception Hierarchy
The exception hierarchy includes Error
, VirtualMachineError
, OutOfMemoryError
, Throwable
, Exception
, RuntimeException
, IOException
, NullPointerException
, ArithmeticException
, and IndexOutOfBoundsException
.
Try-Catch-Finally
try
block: Contains risky code.catch
block: Responds to exceptions.finally
block: Code that runs at the end, regardless of exceptions.- Multiple catch blocks can handle different exception types.
- Example:
java
try {
// risky code
} catch (IOException e) {
// respond to exception
} catch (Exception e) {
// respond to exception
}
Stack Unwinding
- If an exception is thrown but not caught in a scope:
- The method terminates, and local variables are lost.
- Control returns to the caller to find a catch block.
- This repeats until caught or the main method terminates.
File IO and Exceptions
- File IO methods often throw
IOExceptions
, requiring try-catch blocks. - All file access should be within a try/catch block to handle exceptions.
Try-With-Resources
- Java provides try-with-resources for automatic resource management.
- Resources declared next to try are automatically closed.
- Example:
java
try (FileWriter fw = new FileWriter(“myFile.txt”)) {
// write data to file
} catch (Exception e) {
// respond to any exception
}
Demos
Mismatch.java
: Generates InputMismatchException
, ArithmeticException
, and demonstrates try/catch.ReliableNextInt.java
: Uses exception handling to retry until successfully reading an integer.Unwinding.java
: Shows “stack unwinding”.OrderMatters.java
: Demonstrates the importance of the order in which exceptions are caught.MyExceptionTest.java
: Creating, throwing, and catching a custom exception.
Exceptions - Summary
- Exceptions represent “exceptional” problems needing immediate attention.
- Exceptions are thrown when a problem is detected.
- Exceptions are caught using try-catch blocks.
- The stack is unwound to find a handler.
Flow of Control
- Includes sequential, conditional, loop, call/return, and throw/catch (non-local) control flows.
IO Streams
Concept: Streams
- All IO in Java is derived from Byte Streams (sequences of 8-bit values).
- Base classes:
InputStream
and OutputStream
. - File-specific subclasses:
FileInputStream
and FileOutputStream
. - These classes provide low-level operations, often requiring more featured alternatives.
- Classes for reading/writing byte streams.
- Methods include
read()
, reset()
, skip()
, close()
, write()
. - Can read individual bytes or arrays.
- More info: https://docs.oracle.com/en/java/javase/11/docs/api/ java.base/java/io/FileInputStream.html
Reading Streams
- The
Scanner()
class can read from the InputStream
base class. - Example:
FileInputStream iStream = new FileInputStream("file.txt"); Scanner scnr = new Scanner(iStream);
Writing Streams
FileOutputStream()
: Base class for writing a byte stream to a file.PrintWriter()
: Encapsulates the above for easier string usage (provides print()
, println()
, and format()
methods).
Writing Text Files
- Example with writer:
java
FileWriter fw = new FileWriter("file.txt");
PrintWriter oWriter = new PrintWriter(oStream);
oWriter.print("Hello, world!");
- Example with streams:
java
FileOutputStream oStream = new FileOutputStream("file.txt");
PrintWriter oWriter = new PrintWriter(oStream);
oWriter.print("Hello, world!");
Binary Streams
- Binary mode streams can be more efficient than character mode in time and space.
- Example: The number 3.141592653589793:
- As a double: 8 bytes
- As characters: 17 characters * 2 bytes (unicode) = 34 bytes
- Reading as a character stream requires conversion from String to double, which takes more time.
Data Streams
DataOutputStream
and DataInputStream
can write/read primitive values or Strings to a file using binary representation.- Binary representation lacks lines, spaces, or tokens, necessitating a serialization strategy.
- More info: https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
Extended Example: Word Embeddings
- Represent words as vectors in high-dimensional space for natural language processing.
Vectors
- Sequential data structures like arrays.
- Represent coordinates in 2D, 3D, or N-dimensional space.
- Example:
- u = [3.5, 4.5]
- v = [5.5, 2.0]
- u + v = [9.0, 6.5]
Dot Product
- Vector operation that returns a scalar.
- Formula: u \cdot v = u1v1 + u2v2 + \ldots + uDvD
- If:
- u = [3.5, 4.5]
- v = [5.5, 2.0]
- Then:
- u \cdot v = 3.5 * 5.5 + 4.5 * 2.0 = 28.25
- Length of vector:
Similarity
- The dot product measures similarity between vectors:
- Cos(\theta) = \frac{u \cdot v}{|u| |v|}
Distance
- The dot product measures distance between vectors:
- |u - v| = \sqrt{(u1 - v1)^2 + \ldots + (un - vn)^2}
Example Embeddings
- Examples of word embeddings are shown in a 2D graph.
- See the original paper: https://nlp.stanford.edu/projects/glove/
Example: Embeddings V1 (Text)
- File Size: 163MB
- Load Time (sec): 67.251
Example: Embeddings V2 (Text)
- File Size: 163MB
- Load Time (sec): 3.413
Example: Embeddings V3 (DataStream)
- File Size: 80MB
- Load Time (sec): 0.934
Example: Embeddings V4 (ObjectStream)
- File Size: 80MB
- Load Time (sec): 0.927
- 400,000 words, 50 floats per word (= 20 million floats).
Summary
- Exception Handling:
- Control flow for unexpected conditions.
- Handled with try/catch/finally, and throw.
- File IO:
- Files contain streams of characters/bytes.
- Large set of classes for different views.
- Binary mode IO can be faster and more efficient.
Wrapping Up
- File IO isn't much more complex than regular IO (at least with plain text).
- Exceptions provide a new form of flow control for handling errors and exceptions.