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.
Basic structure:java try { // risky code } catch (Exception e) { // respond to exception }
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.
The exception hierarchy includes Error
, VirtualMachineError
, OutOfMemoryError
, Throwable
, Exception
, RuntimeException
, IOException
, NullPointerException
, ArithmeticException
, and IndexOutOfBoundsException
.
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 }
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 methods often throw IOExceptions
, requiring try-catch blocks.
All file access should be within a try/catch block to handle exceptions.
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 }
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 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.
Includes sequential, conditional, loop, call/return, and throw/catch (non-local) control flows.
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
The Scanner()
class can read from the InputStream
base class.
Example: FileInputStream iStream = new FileInputStream("file.txt"); Scanner scnr = new Scanner(iStream);
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).
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 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.
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
Represent words as vectors in high-dimensional space for natural language processing.
Sequential data structures like arrays.
Represent coordinates in 2D, 3D, or N-dimensional space.
Example:
u=[3.5,4.5]$$u = [3.5, 4.5]$$
v=[5.5,2.0]$$v = [5.5, 2.0]$$
u+v=[9.0,6.5]$$u + v = [9.0, 6.5]$$
Vector operation that returns a scalar.
Formula: $$u \cdot v = u1v1 + u2v2 + \ldots + uDvD$$
If:
u=[3.5,4.5]$$u = [3.5, 4.5]$$
v=[5.5,2.0]$$v = [5.5, 2.0]$$
Then:
u⋅v=3.5∗5.5+4.5∗2.0=28.25$$u \cdot v = 3.5 * 5.5 + 4.5 * 2.0 = 28.25$$
Length of vector:
∣u∣=u⋅u$$|u| = \sqrt{u \cdot u}$$
The dot product measures similarity between vectors:
Cos(θ)=∣u∣∣v∣u⋅v$$Cos(\theta) = \frac{u \cdot v}{|u| |v|}$$
The dot product measures distance between vectors:
$$|u - v| = \sqrt{(u1 - v1)^2 + \ldots + (un - vn)^2}$$
Examples of word embeddings are shown in a 2D graph.
See the original paper: https://nlp.stanford.edu/projects/glove/
File Size: 163MB
Load Time (sec): 67.251
File Size: 163MB
Load Time (sec): 3.413
File Size: 80MB
Load Time (sec): 0.934
File Size: 80MB
Load Time (sec): 0.927
400,000 words, 50 floats per word (= 20 million floats).
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.
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.
Exception Handling and Binary Mode
java
try {
// risky code
} catch (Exception e) {
// respond to exception
}
OutOfMemoryError
, StackOverflowError
, NullPointerException
The exception hierarchy includes Error
, VirtualMachineError
, OutOfMemoryError
, Throwable
, Exception
, RuntimeException
, IOException
, NullPointerException
, ArithmeticException
, and IndexOutOfBoundsException
.
try
block: Contains risky code.catch
block: Responds to exceptions.finally
block: Code that runs at the end, regardless of exceptions.java
try {
// risky code
} catch (IOException e) {
// respond to exception
} catch (Exception e) {
// respond to exception
}
IOExceptions
, requiring try-catch blocks.java
try (FileWriter fw = new FileWriter(“myFile.txt”)) {
// write data to file
} catch (Exception e) {
// respond to any exception
}
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.InputStream
and OutputStream
.FileInputStream
and FileOutputStream
.read()
, reset()
, skip()
, close()
, write()
.Scanner()
class can read from the InputStream
base class.FileInputStream iStream = new FileInputStream("file.txt"); Scanner scnr = new Scanner(iStream);
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).java
FileWriter fw = new FileWriter("file.txt");
PrintWriter oWriter = new PrintWriter(oStream);
oWriter.print("Hello, world!");
java
FileOutputStream oStream = new FileOutputStream("file.txt");
PrintWriter oWriter = new PrintWriter(oStream);
oWriter.print("Hello, world!");
DataOutputStream
and DataInputStream
can write/read primitive values or Strings to a file using binary representation.