w3resource

Java Program: File reading and exception handling for positive numbers

Java Exception Handling: Exercise-4 with Solution

Write a Java program that reads a list of numbers from a file and throws an exception if any of the numbers are positive.

Sample Solution:

Java Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class File_Read {
  public static void main(String[] args) {
    try {
      readFile("test1.txt");
    } catch (FileNotFoundException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }

  public static void readFile(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    Scanner scanner = new Scanner(file);

    // Read and process the contents of the file
    while (scanner.hasNextLine()) {
      String line = scanner.nextLine();
      System.out.println(line);
    }

    scanner.close();
  }
}

Sample Output:

Content of test.txt:
-1
-2
-3
-4

All numbers are non-positive.
Content of test.txt:
-1
-2
-3
4

Error: Positive number found: 4

Explanation:

The above code demonstrates how to read numbers from a file and throw a custom exception if any are positive. It showcases the use of exception handling and the creation of custom exceptions in Java.

Here are some important points:

  • The PositiveNumberException class is a custom exception class that extends the base Exception class. It provides a constructor that takes a message parameter and passes it to the superclass constructor using the super keyword.
  • If a FileNotFoundException occurs in the main method, it is caught and an appropriate error message is printed.
  • If a PositiveNumberException occurs in the checkNumbersFromFile method, it is caught in the main method. The error message indicating a positive number is printed.

Flowchart:

Flowchart: Java Program: File reading and exception handling for positive numbers

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: File reading method with exception handling.
Next: File reading and empty file exception handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.