exception handling and basic file operations in Java

This commit is contained in:
2026-07-12 18:11:19 +03:30
parent 36154a9560
commit 08754f98f4
2 changed files with 61 additions and 42 deletions
@@ -19,44 +19,58 @@ public class RuntimeExceptionDemo {
//nullPointerException
//IllegalArgumentException
public static void validateEmail(UserEntity user) {
try {
String email = user.getEmail();
String email = user.getEmail();
String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (!Pattern.matches(emailRegex, email)) {
throw new IllegalArgumentException("Invalid email format");
}
if (!Pattern.matches(emailRegex, email)) {
throw new IllegalArgumentException("Invalid email format");
System.out.println("User email is valid");
} catch (NullPointerException e) {
System.out.println("Error: email is null - " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("User email is valid");
}
// ArithmeticException
public static void calculatePayment(int totalAmount, int installmentCount) {
try {
int payment = totalAmount / installmentCount;
int payment = totalAmount / installmentCount;
System.out.println("Each installment : " + payment);
System.out.println("Each installment : " + payment);
} catch (ArithmeticException e) {
System.out.println("Error: cannot divide by zero - " + e.getMessage());
}
}
// NumberFormatException
public static void convertUserAge(String ageInput) {
try {
int age = Integer.parseInt(ageInput);
int age = Integer.parseInt(ageInput);
System.out.println("User age: " + age);
System.out.println("User age: " + age);
} catch (NumberFormatException e) {
System.out.println("Error: invalid number format - " + e.getMessage());
}
}
// IllegalStateException
public static void completeRegistration(UserEntity user) {
try {
if (user.getDateOfBirth() == null) {
throw new IllegalStateException(
"Registration cannot be completed. Date of birth is missing."
);
}
if (user.getDateOfBirth() == null) {
throw new IllegalStateException(
"Registration cannot be completed. Date of birth is missing."
);
System.out.println("Registration completed");
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Registration completed");
}
}