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 Positive_Number_Check {
public static void main(String[] args) {
try {
checkNumbersFromFile("test.txt");
System.out.println("All numbers are non-positive.");
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (PositiveNumberException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void checkNumbersFromFile(String fileName) throws FileNotFoundException, PositiveNumberException {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int number = Integer.parseInt(scanner.nextLine());
if (number > 0) {
throw new PositiveNumberException("Positive number found: " + number);
}
}
scanner.close();
}
}
class PositiveNumberException extends Exception {
public PositiveNumberException(String message) {
super(message);
}
}
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.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/exception/java-exception-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics