0% found this document useful (0 votes)
1 views13 pages

NAME: Ayesha Tariq REG NO: F24605102 Submitted To: Mam Tayyaba

The document contains multiple Java programming tasks focused on exception handling and user input validation. Each task demonstrates different scenarios, such as logging file read errors, validating user input for name, age, and email, managing bank transactions with insufficient funds, and handling array index access errors. The code snippets illustrate the implementation of custom exceptions and error handling techniques in Java.

Uploaded by

sattiuzair99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views13 pages

NAME: Ayesha Tariq REG NO: F24605102 Submitted To: Mam Tayyaba

The document contains multiple Java programming tasks focused on exception handling and user input validation. Each task demonstrates different scenarios, such as logging file read errors, validating user input for name, age, and email, managing bank transactions with insufficient funds, and handling array index access errors. The code snippets illustrate the implementation of custom exceptions and error handling techniques in Java.

Uploaded by

sattiuzair99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

NAME : Ayesha tariq

REG NO : F24605102
SUBMITTED TO : MAM TAYYABA

Task #01
import java.io.*; interface

Logger { void log(String

message); void

log(Exception e);

class ConsoleLogger implements Logger {

@Override public void

log(String message) {

System.out.println("LOG: " + message);

@Override public void

log(Exception e) {

System.out.println("EXCEPTION: " + e.getClass().getSimpleName() + " - " + e.getMessage());

public class FileReadWithLogging {

public static void main(String[] args) {

Logger logger = new ConsoleLogger();

String filePath = "input.txt";

try {

try {

BufferedReader reader = new BufferedReader(new FileReader(filePath));

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);
}

reader.close();

} catch (FileNotFoundException fnfe) {

logger.log(fnfe);

} catch (IOException ioe) {

logger.log(ioe);

Output

Task #02
import java.util.Scanner; class

InvalidNameException extends Exception {

public InvalidNameException(String message) {

super(message);

class InvalidEmailException extends Exception {

public InvalidEmailException(String message) {

super(message);
}

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

public class UserInputValidator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try

System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.print("Enter your age: ");

String ageStr = scanner.nextLine(); System.out.print("Enter your email: ");

String email = scanner.nextLine();


validateName(name);

int age = validateAge(ageStr);

validateEmail(email);

System.out.println("\nUser input is valid!");

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Email: " + email);

} catch (InvalidNameException | InvalidAgeException | InvalidEmailException e) {

System.out.println("Input Error: " + e.getMessage());

scanner.close();

private static void validateName(String name) throws InvalidNameException {

if (name == null || name.trim().isEmpty()) { throw new

InvalidNameException("Name cannot be empty.");

if (!name.matches("[a-zA-Z\\s]+")) { throw new

InvalidNameException("Name must contain only letters and spaces.");

}
private static int validateAge(String ageStr) throws InvalidAgeException {

try {

int age = Integer.parseInt(ageStr); if (age < 1 || age > 120) {

throw new InvalidAgeException("Age must be between 1 and 120.");

return age;

} catch (NumberFormatException e) { throw new

InvalidAgeException("Age must be a valid number.");

private static void validateEmail(String email) throws InvalidEmailException {

if (email == null || email.trim().isEmpty()) { throw new

InvalidEmailException("Email cannot be empty.");

if (!email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$")) {

throw new InvalidEmailException("Email format is invalid.");

}
Output

Task #03
import java.util.Scanner; class

InsufficientFundsException extends Exception {

public InsufficientFundsException(String message) {

super(message);

class BankAccount {

private double balance;

public BankAccount(double initialBalance) {

this.balance = initialBalance;

public void withdraw(double amount) throws InsufficientFundsException { if


(amount > balance) {

throw new InsufficientFundsException("Insufficient funds. Current balance: $" +


balance);
}

balance -= amount;

System.out.println("Withdrawal successful. Remaining balance: $" + balance);

public double getBalance() {

return balance;

public class TransactionSystem {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

BankAccount account = new BankAccount(500.00);

boolean success = false;

while (!success) {

System.out.println("\nCurrent balance: $" + account.getBalance());

System.out.print("Enter amount to withdraw: ");

double amount;

try {
amount = Double.parseDouble(scanner.nextLine());

account.withdraw(amount); success = true;

} catch (InsufficientFundsException e) {

System.out.println("Error: " + e.getMessage());

System.out.println("Please enter a new amount.");

} catch (NumberFormatException e) {

System.out.println("Invalid input. Please enter a numeric amount.");

scanner.close();

Output

Task #04
import java.util.Scanner; public class

ArrayAccessDemo { public static void

main(String[] args) { Scanner scanner = new

Scanner(System.in);
try {

System.out.print("Enter the size of the array: ");

int size = scanner.nextInt();

int[] numbers = new int[size];

System.out.println("Enter " + size + " integers:");

for (int i = 0; i < size; i++) { numbers[i] =

scanner.nextInt();

System.out.print("Enter the index you want to access (try an invalid one): ");

int index = scanner.nextInt();

System.out.println("Value at index " + index + ": " + numbers[index]);

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Error: You tried to access an index that is out of bounds.");

System.out.println("Exception message: " + e.getMessage());

} catch (Exception e) {

System.out.println("An unexpected error occurred: " + e.getMessage());

} finally {

scanner.close();

System.out.println("Program finished.");
}

Output

Task #05
import java.util.Scanner; class

InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

public class AgeValidator { public

static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try

System.out.print("Enter your age: ");

int age = scanner.nextInt();


validateAge(age);

System.out.println("Age is valid: " + age);

} catch (InvalidAgeException e) {

System.out.println("Invalid Age: " + e.getMessage());

} catch (Exception e) {

System.out.println("Unexpected error: " + e.getMessage());

} finally {

scanner.close();

public static void validateAge(int age) throws InvalidAgeException {

if (age == 0) {

throw new InvalidAgeException("Age cannot be zero.");

} else if (age < 18) { throw new

InvalidAgeException("Age must be at least 18.");

} else if (age > 90) {

throw new InvalidAgeException("Age cannot be more than 90.");

Output

You might also like