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.

Object ↓ ThrowableExceptionRuntimeException

Important Classes:

ClassDescription
ThrowableParent of all exceptions
ExceptionRecoverable exceptions
RuntimeExceptionOccur at runtime
ErrorSerious system problems

Types of Exceptions:

  1. Checked Exceptions

    • Checked at compile time

    • Example: IOException, SQLException

  2. Unchecked Exceptions

    • Checked at runtime

    • Example: NullPointerException, ArithmeticException

  3. Errors

    • Not handled by program

    • Example: OutOfMemoryError

Throwing and Catching Exceptions

Try-Catch Block

Used to handle exceptions.

try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }

Flow:

  • Code in try runs
  • If error occurs → control goes to catch

Finally Block

Always executes, whether exception occurs or not.

finally { System.out.println("This always executes"); }

Throwing Exceptions (throw)

Used to manually throw an exception.

throw new ArithmeticException("Invalid operation");

Declaring Exceptions (throws)

Used to declare exceptions to be handled later.

void readFile() throws IOException { // file code }

Built-in Exceptions

Java provides many predefined exceptions.

ExceptionCause
ArithmeticExceptionDivide by zero
NullPointerExceptionAccessing null object
ArrayIndexOutOfBoundsExceptionInvalid array index
NumberFormatExceptionInvalid number format
IOExceptionInput-output failure
ClassNotFoundExceptionClass not found

Creating Own (User-Defined) Exceptions

Java allows creating custom exceptions.

Steps:

  1. Extend Exception or RuntimeException
  2. Define constructor
  3. Throw it when needed

Example:

class AgeException extends Exception { AgeException(String msg) { super(msg); } } class Test { public static void main(String args[]) throws AgeException { int age = 15; if (age < 18) { throw new AgeException("Age must be 18 or above"); } } }

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:

try { int a = 10 / 0; } catch (Exception e) { e.printStackTrace(); }

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:

  1. Input Stream – Reads data
  2. 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

ClassPurpose
FileInputStreamReads data from file
FileOutputStreamWrites data to file
BufferedInputStreamFaster reading
BufferedOutputStreamFaster writing

Example: Reading File using Byte Stream

import java.io.*; class ByteRead { public static void main(String args[]) throws Exception { FileInputStream fis = new FileInputStream("data.txt"); int i; while ((i = fis.read()) != -1) { System.out.print((char)i); } fis.close(); } }

Example: Writing File using Byte Stream

import java.io.*; class ByteWrite { public static void main(String args[]) throws Exception { FileOutputStream fos = new FileOutputStream("data.txt"); String msg = "Hello Java"; fos.write(msg.getBytes()); fos.close(); } }

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

ClassPurpose
FileReaderReads text file
FileWriterWrites text file
BufferedReaderEfficient reading
BufferedWriterEfficient writing

Example: Reading File using Character Stream

import java.io.*; class CharRead { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("data.txt"); int i; while ((i = fr.read()) != -1) { System.out.print((char)i); } fr.close(); } }

Example: Writing File using Character Stream

import java.io.*; class CharWrite { public static void main(String args[]) throws Exception { FileWriter fw = new FileWriter("data.txt"); fw.write("Welcome to Java I/O"); fw.close(); } }

Difference Between Byte Stream and Character Stream

FeatureByte StreamCharacter Stream
Data typeBytesCharacters
Best forBinary filesText files
Base classesInputStream / OutputStreamReader / Writer
EncodingNot handledHandles Unicode

Reading and Writing Data

Java provides different ways to read and write data:

Source / DestinationClasses Used
KeyboardScanner, BufferedReader
FileFileInputStream, FileReader
ConsoleSystem.in, System.out
NetworkInputStream, OutputStream

Console Reading

Using Scanner Class

import java.util.Scanner; class ConsoleInput { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter name: "); String name = sc.nextLine(); System.out.println("Hello " + name); } }

Advantages:

  • Easy to use
  • Reads different data types

Using BufferedReader

import java.io.*; class ConsoleRead { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String name = br.readLine(); System.out.println("Welcome " + name); } }

Advantage:

  • Faster than Scanner

Console Writing

Using System.out

System.out.println("Java I/O Output");

  • print() → No new line
  • println() → New line

File Reading and Writing

Steps:

  1. Create stream object
  2. Read or write data
  3. Close stream

Example: Copy File (Character Stream)

import java.io.*; class FileCopy { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("input.txt"); FileWriter fw = new FileWriter("output.txt"); int i; while ((i = fr.read()) != -1) { fw.write(i); } fr.close(); fw.close(); } }

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.