2 Exception Handling And Input Output

Advanced Java Programming · Unit 2

Exception Handling and Input/Output

Exam-focused notes for Exception Handling and Input/Output (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 4 solved past questions from this unit.

Exception Handling and Input/Output in short

Programs meet errors and must also read and write data. This chapter shows how Java handles run-time errors with exceptions and how it works with files and objects.

Exception Handling and Input/Output: notes

Exception types and hierarchy

An exception is an event that breaks the normal flow of a program, such as dividing by zero. Java represents it as an object. All of them descend from Throwable, which has two branches: Error and Exception.

  • Error means a serious JVM problem, such as OutOfMemoryError. We do not usually catch it.
  • Checked exceptions are subclasses of Exception outside RuntimeException. The compiler forces you to catch or declare them. Examples are IOException and SQLException.
  • Unchecked exceptions are subclasses of RuntimeException. The compiler does not force handling. Examples are ArithmeticException, NullPointerException and ArrayIndexOutOfBoundsException.
Throwable
 +-- Error
 +-- Exception
      +-- IOException (checked)
      +-- RuntimeException (unchecked)

Try-catch-finally blocks

Code that may fail goes in a try block. Each catch block handles one exception type. The finally block runs whether or not an exception happened, so it is used to release resources.

public class TryDemo {
    public static void main(String[] args) {
        try {
            int[] a = new int[3];
            a[5] = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Divide by zero: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Other: " + e);
        } finally {
            System.out.println("Always runs");
        }
    }
}

Rules to remember:

  • A try block needs at least one catch or a finally.
  • Catch the specific exception first and the general Exception last.
  • throw throws one exception object. throws lists exceptions a method may pass on.
  • Try-with-resources closes resources by itself.

What this unit covers

  • Exception types and hierarchy
  • Try-catch-finally blocks
  • Custom exception throwing
  • File I/O operations
  • Reading from keyboard and writing to files
  • Random file access
  • Serialization and object persistence

Custom exception throwing

2082 · 10 marks

List some features of Java. What are the types of exception? Write a program to take input an integer from the user and if the given integer is negative throw the exception.[10]

Show solved answer

Model Answer: Features of Java, Exception Types, and Exception Handling Program

Features of Java (3 marks)

Key features of Java include:

  1. Object-Oriented: Java is purely object-oriented, based on classes and objects. Everything is an object except primitive data types.

  2. Platform Independent: Java follows "Write Once, Run Anywhere" (WORA) principle. Code compiled to bytecode runs on any platform with JVM.

  3. Simple and Familiar: Java syntax is similar to C/C++, making it easy to learn for programmers familiar with these languages.

  4. Secure: Java provides built-in security features like bytecode verification, exception handling, and no pointer arithmetic.

  5. Robust: Strong memory management, automatic garbage collection, and exception handling make Java robust.

  6. Multithreaded: Java supports concurrent programming through built-in threading capabilities.

  7. Dynamic: Java supports dynamic loading of classes at runtime.


Types of Exceptions (3 marks)

Exceptions in Java are classified as:

1. Checked Exceptions

  • Exceptions that must be caught or declared in the method signature
  • Checked at compile time
  • Examples: IOException, SQLException, FileNotFoundException

2. Unchecked Exceptions

  • Exceptions that need not be caught or declared
  • Checked at runtime
  • Derived from RuntimeException class
  • Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException

3. Error

  • Serious problems that should not be caught
  • Examples: StackOverflowError, OutOfMemoryError

Program: Exception Handling for Negative Integer (4 marks)

import java.util.Scanner;

public class NegativeNumberException {
    
    // Custom exception class
    static class NegativeNumberException extends Exception {
        public NegativeNumberException(String message) {
            super(message);
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        try {
            System.out.print("Enter an integer: ");
            int number = sc.nextInt();
            
            // Check if number is negative and throw exception
            if (number < 0) {
                throw new NegativeNumberException("Error: Negative number not allowed!");
            }
            
            System.out.println("You entered: " + number);
            
        } catch (NegativeNumberException e) {
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            sc.close();
            System.out.println("Program terminated.");
        }
    }
}

Output Example:

Enter an integer: -5
Exception caught: Error: Negative number not allowed!
Program terminated.

Explanation:

  • A custom exception class NegativeNumberException extends Exception (checked exception)
  • User input is taken using Scanner
  • If the number is negative, the exception is thrown with a message
  • The catch block handles the thrown exception
  • The finally block executes regardless of exception occurrence
Open this answer on its own page →

Random file access

2082 · 5 marks

How do you access file randomly? Give an example. [5]

Random file access (also called direct access or seek access) allows you to read or write data at any position in a file without having to read through all preceding data sequentially. This is in contrast to sequential access where you must read from the beginning. The key steps are: 1. Open the ...

Open this answer on its own page →

Exception types and hierarchy

2080 · 5 marks

Describe about exception handlings with example. [5]

Exception handling is a mechanism in programming that allows a program to detect, manage, and respond to runtime errors (exceptions) gracefully without terminating abruptly. It enables the program to continue execution or terminate in a controlled manner when unexpected situations occur. Contains...

Open this answer on its own page →

Reading from keyboard and writing to files

0 · 5 marks

Write a java program to read content from keyboard and write it to the file named test.txt in D: drive. [5]

  1. FileWriter: Opens file "D:\test.txt" for writing (creates if doesn't exist) 2. BufferedWriter: Wraps FileWriter for efficient buffered output 3. InputStreamReader: Converts keyboard input stream to character stream 4. BufferedReader: Wraps InputStreamReader for efficient line-by-line reading ...
Open this answer on its own page →