Unit 3: Exception Handling, I/O
Exception Handling in Java
An exception is an unexpected problem that occurs during the execution of a program and disrupts normal flow.
Simple meaning: An exception is an error that happens while the program is running.
Real-life example:
- Dividing a number by zero
- Opening a file that does not exist
If exceptions are not handled, the program crashes.
Exception Hierarchy in Java
Java exceptions follow a tree structure called the exception hierarchy.
Important Classes:
| Class | Description |
|---|---|
| Throwable | Parent of all exceptions |
| Exception | Recoverable exceptions |
| RuntimeException | Occur at runtime |
| Error | Serious system problems |
Types of Exceptions:
-
Checked Exceptions
-
Checked at compile time
-
Example: IOException, SQLException
-
-
Unchecked Exceptions
-
Checked at runtime
-
Example: NullPointerException, ArithmeticException
-
-
Errors
-
Not handled by program
-
Example: OutOfMemoryError
-
Throwing and Catching Exceptions
Try-Catch Block
Used to handle exceptions.
Flow:
- Code in
tryruns - If error occurs → control goes to
catch
Finally Block
Always executes, whether exception occurs or not.
Throwing Exceptions (throw)
Used to manually throw an exception.
Declaring Exceptions (throws)
Used to declare exceptions to be handled later.
Built-in Exceptions
Java provides many predefined exceptions.
| Exception | Cause |
|---|---|
| ArithmeticException | Divide by zero |
| NullPointerException | Accessing null object |
| ArrayIndexOutOfBoundsException | Invalid array index |
| NumberFormatException | Invalid number format |
| IOException | Input-output failure |
| ClassNotFoundException | Class not found |
Creating Own (User-Defined) Exceptions
Java allows creating custom exceptions.
Steps:
- Extend
ExceptionorRuntimeException - Define constructor
- Throw it when needed
Example:
Use:
- Business rules
- Validation errors
Stack Trace Elements
A stack trace shows:
- Sequence of method calls
- Where the exception occurred
Simple meaning: It is a roadmap of program execution at the time of error.
StackTraceElement Class
Java uses StackTraceElement class to represent stack trace details.
Information Provided:
- Class name
- Method name
- File name
- Line number
Example:
Why Stack Trace is Important?
- Helps in debugging
- Identifies exact error location
- Shows method call flow
I/O Exceptions (Overview)
Input/Output operations often cause exceptions.
Examples:
- File not found
- Disk read/write error
- Network failure
Common I/O Exceptions:
- IOException
- FileNotFoundException
- EOFException
Conclusion
Exception handling in Java helps to:
- Prevent program crashes
- Handle runtime problems smoothly
- Improve program reliability
- Debug errors effectively
Understanding exception hierarchy, try-catch, built-in exceptions, custom exceptions, and stack trace is essential for Java programming, exams, and interviews.
Introduction to Input / Output (I/O) in Java
Input / Output (I/O) in Java is used to read data (input) and write data (output).
Simple meaning:
- Input → Getting data into the program
- Output → Sending data out of the program
Examples:
- Reading data from keyboard
- Writing data to a file
- Displaying output on screen
Java handles I/O using streams.
What is a Stream?
A stream is a flow of data from one place to another.
Types of Streams:
- Input Stream – Reads data
- Output Stream – Writes data
Byte Streams
Byte streams handle data byte by byte (8 bits).
Used for:
- Images
- Audio files
- Video files
- Binary data
Main Classes:
InputStream- OutputStream
Common Byte Stream Classes
| Class | Purpose |
|---|---|
| FileInputStream | Reads data from file |
| FileOutputStream | Writes data to file |
| BufferedInputStream | Faster reading |
| BufferedOutputStream | Faster writing |
Example: Reading File using Byte Stream
Example: Writing File using Byte Stream
Character Streams
Character streams handle data character by character (Unicode).
Used for:
- Text files
- Letters, numbers, symbols
Main Classes:
Reader- Writer
Common Character Stream Classes
| Class | Purpose |
|---|---|
| FileReader | Reads text file |
| FileWriter | Writes text file |
| BufferedReader | Efficient reading |
| BufferedWriter | Efficient writing |
Example: Reading File using Character Stream
Example: Writing File using Character Stream
Difference Between Byte Stream and Character Stream
| Feature | Byte Stream | Character Stream |
|---|---|---|
| Data type | Bytes | Characters |
| Best for | Binary files | Text files |
| Base classes | InputStream / OutputStream | Reader / Writer |
| Encoding | Not handled | Handles Unicode |
Reading and Writing Data
Java provides different ways to read and write data:
| Source / Destination | Classes Used |
|---|---|
| Keyboard | Scanner, BufferedReader |
| File | FileInputStream, FileReader |
| Console | System.in, System.out |
| Network | InputStream, OutputStream |
Console Reading
Using Scanner Class
Advantages:
- Easy to use
- Reads different data types
Using BufferedReader
Advantage:
-
Faster than Scanner
Console Writing
Using System.out
print()→ No new lineprintln()→ New line
File Reading and Writing
Steps:
- Create stream object
- Read or write data
- Close stream
Example: Copy File (Character Stream)
Conclusion
Java I/O provides powerful features to:
- Read data from keyboard
- Write output to console
- Handle text and binary files efficiently
Understanding byte streams, character streams, console I/O, and file handling is essential for Java programming, exams, and real-world applications.