Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Exercise 7c

Name: Piyush Verma


RegNo: 23MCA1104

Ques�on 1:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOExcep�on;

public class Main {


public sta�c void main(String[] args) {
// Atempt to read data from the file
try {
BufferedReader reader = new BufferedReader(new
FileReader("input.txt"));
String line;
// Print each line of the file
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOExcep�on e) {
// Handle the excep�on if the file cannot be read
System.out.println("Error: Cannot read from file. Please check
if the file exists.");
}
}
}
Output:

Ques�on 2:

import java.lang.reflect.Invoca�onTargetExcep�on;
import java.u�l.Scanner;

public class Main {


public sta�c void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the fully qualified name of a class
System.out.print("Enter the fully qualified name of a class: ");
String className = scanner.nextLine();
try {
// Load the specified class dynamically
Class<?> clazz = Class.forName(className);
// Instan�ate the class using reflec�on
Object object = clazz.getDeclaredConstructor().newInstance();
System.out.println("Successfully loaded and instan�ated class:
" + object.getClass().getName());
} catch (ClassNotFoundExcep�on e) {
// Handle the excep�on if the specified class cannot be found
System.out.println("Error: Class not found. Please enter a valid
class name.");
} catch (Instan�a�onExcep�on | IllegalAccessExcep�on |
NoSuchMethodExcep�on | Invoca�onTargetExcep�on e) {
// Handle other reflec�on-related excep�ons
System.out.println("Error: Could not instan�ate class. Please
ensure the class has a public no-argument constructor.");
}
// Close the scanner
scanner.close();
}
}
Output:

You might also like