Java Exception Handling Solutions
Assignment 1.1.a: Basic Exception Handling
Problem Statement:
Write a Java program that takes two integers as input and performs division. Use exception handling to ma
Solution:
```java
import java.util.Scanner;
public class DivisionHandler {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (Exception e) {
System.out.println("Error: Invalid input.");
} finally {
scanner.close();
}
}
}
```
Assignment 1.1.b: Custom Age Exception
Problem Statement:
Create a custom exception class `AgeOutOfRangeException`. Throw this exception if the age is less than 0
Solution:
```java
import java.util.Scanner;
class AgeOutOfRangeException extends Exception {
public AgeOutOfRangeException(String message) {
super(message);
}
}
public class AgeValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter age: ");
int age = scanner.nextInt();
if (age < 0 || age > 120) {
throw new AgeOutOfRangeException("Error: Age " + age + " is out of valid range.");
}
System.out.println("Age is valid.");
} catch (AgeOutOfRangeException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}
```