0% found this document useful (0 votes)
8 views2 pages

java_exception_handling_solutions

The document outlines two Java assignments focused on exception handling. The first assignment involves creating a program that divides two integers with error handling for division by zero and invalid input. The second assignment requires the creation of a custom exception class for validating age, throwing an exception if the age is out of the specified range.

Uploaded by

Techno VSP
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)
8 views2 pages

java_exception_handling_solutions

The document outlines two Java assignments focused on exception handling. The first assignment involves creating a program that divides two integers with error handling for division by zero and invalid input. The second assignment requires the creation of a custom exception class for validating age, throwing an exception if the age is out of the specified range.

Uploaded by

Techno VSP
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/ 2

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();
}
}
}
```

You might also like