Name-Aryan
Roll no-2200290530024
Sec- A
JAVA ASSIGNMENT-02
1). WAP to create a method that reads a file and throws an exception if
the file
import [Link];
import [Link];
import [Link];
public class FileReadingExample {
public static void readFile(String filePath) throws Exception {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line;
[Link]("File content:");
while ((line = [Link]()) != null) {
[Link](line);
} catch (IOException e) {
throw new Exception("An error occurred while reading the file: " + [Link]());
} finally {
if (reader != null) {
try {
[Link]();
} catch (IOException e) {
throw new Exception("An error occurred while closing the file: " + [Link]());
Name-Aryan
Roll no-2200290530024
Sec- A
public static void main(String[] args) {
String filePath = "[Link]";
try {
readFile(filePath);
} catch (Exception e) {
[Link]([Link]());
2).WAP to Check Array Bounds while Inputting Elements into an Array.
import [Link];
public class ArrayBoundsCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int size = [Link]();
int[] array = new int[size];
[Link]("Enter " + size + " elements:");
Name-Aryan
Roll no-2200290530024
Sec- A
for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": ");
if ([Link]()) {
array[i] = [Link]();
} else {
[Link]("Invalid input. Please enter an integer.");
[Link](); // Clear the invalid input
i--; // Decrement i to retry the current index
[Link]("Array elements:");
for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": " + array[i]);
[Link]();