JAVA EXCEPTION HANDLING LAB-2
Question 1: Arithmetic Exception
Write a Java program that prompts the user to enter two integers, x and y. Implement a try-
catch block to calculate x/y. Catch the Arithmetic Exception if the user enters y=0 and print a
user-friendly error message instead of crashing the program.
SOL: package exceptionhandlinglab3;
import [Link];
public class ques1 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter integer x: ");
int x = [Link]();
[Link]("Enter integer y: ");
int y = [Link]();
try {
int result = x / y;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
[Link]();
}
}
OUTPUT: Enter integer x: 20
Enter integer y: 5
Result: 4
Question 2: Array Index Out of Bounds
Create a Java program that initializes an integer array of size 5. Ask the user for an index and
a value to store at that index. Use a try-catch block to handle the
ArrayIndexOutOfBoundsException if the user enters an invalid index. In the catch block, print
the exception message and then print the valid index range (0 to 4).
SOL: package exceptionhandlinglab3;
import [Link];
public class ques2{
public static void main(String[] args) {
int[] array = new int[5];
Scanner scanner = new Scanner([Link]);
[Link]("Enter index (0-4): ");
int index = [Link]();
[Link]("Enter value: ");
int value = [Link]();
try {
array[index] = value;
[Link]("Value stored successfully.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception: " + [Link]());
[Link]("Valid index range is 0 to 4.");
}
[Link]();
}
}
OUTPUT: Enter index (0-4): 2
Enter value: 25
Value stored successfully.
Question 3: Number Format and Finally Block
Write a program that prompts the user for a string input. Use [Link](String) inside
a try block to convert the string to an integer.
Catch the NumberFormatException if the input is not a valid integer, and print an
appropriate message.
Include a finally block that always executes, regardless of whether an exception occurred,
and prints the message: "Execution attempt finished."
SOL: package exceptionhandlinglab3;
import [Link];
public class ques3{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number as string: ");
String input = [Link]();
try {
int number = [Link](input);
[Link]("You entered: " + number);
} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter a valid integer.");
} finally {
[Link]("Execution attempt finished.");
}
[Link]();
}
}
OUTPUT: Enter a number as string: 123456
You entered: 123456
Execution attempt finished.
Question 4: Division Method with throws
Create a static method named divide(int a, int b) that performs division. This method should
not contain a try-catch block, but should use the throws keyword in its signature to declare
that it might throw an ArithmeticException.
Call this method from the main method and use a try-catch block in main to handle the
potential exception.
SOL: package exceptionhandlinglab3;
import [Link];
public class ques4{
public static int divide(int a, int b) throws ArithmeticException {
return a / b;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter numerator: ");
int a = [Link]();
[Link]("Enter denominator: ");
int b = [Link]();
try {
int result = divide(a, b);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
}
[Link]();
}
}
OUTPUT: Enter numerator: 20
Enter denominator: 10
Result: 2
Question 5: Define a custom unchecked exception class named InvalidInputException that
extends RuntimeException.
Write a method processInput(int number). Inside this method, if the number is negative, use
the throw keyword to explicitly throw a new InvalidInputException with a message like
"Input cannot be negative."
Call processInput() from the main method. Since it's an unchecked exception, you are not
required to use a try-catch block or throws (but you can optionally use try-catch in main to
handle it).
SOL: package exceptionhandlinglab3;
class InvalidInputException extends RuntimeException {
public InvalidInputException(String message) {
super(message);
}
}
public class ques5{
public static void processInput(int number) {
if (number < 0) {
throw new InvalidInputException("Input cannot be negative.");
} else {
[Link]("Valid input: " + number);
}
}
public static void main(String[] args) {
try {
processInput(-5);
} catch (InvalidInputException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}
OUTPUT: Caught Exception: Input cannot be negative.
Question 6: File Not Found Exception
Write a program that attempts to open a file for reading using the [Link]
class (or FileReader or Scanner with a File object).
The file name should be a non-existent file, like "nonexistent_file.txt".
The FileNotFoundException is a checked exception. Handle this exception using a try-catch
block and print an error message including the file name that was not found.
SOL: package exceptionhandlinglab3;
import [Link];
import [Link];
import [Link];
public class ques6{
public static void main(String[] args) {
File file = new File("nonexistent_file.txt");
try {
Scanner scanner = new Scanner(file);
[Link]("File opened successfully.");
[Link]();
} catch (FileNotFoundException e) {
[Link]("Error: File '" + [Link]() + "' not found.");
}
}
}
OUTPUT: Error: File 'nonexistent_file.txt' not found.
Question 7: Multiple Catch Blocks
Create a program that:
Prompts the user for a file name.
Attempts to read the first line of the file (this will throw FileNotFoundException if the file
doesn't exist).
If a line is read, attempts to convert it to an integer (this can throw
NumberFormatException).
Implement multiple catch blocks (most specific first) to handle both FileNotFoundException
and NumberFormatException with different, descriptive messages for each. Include a final,
general catch block for Exception to catch any other unforeseen issues.
SOL: package exceptionhandlinglab3;
import [Link];
import [Link];
import [Link];
public class ques7 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner([Link]);
[Link]("Enter filename: ");
String filename = [Link]();
try {
Scanner fileScanner = new Scanner(new File(filename));
if ([Link]()) {
String line = [Link]();
int number = [Link](line);
[Link]("Parsed number: " + number);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("Error: File not found - " + [Link]());
} catch (NumberFormatException e) {
[Link]("Error: Could not convert line to integer - " + [Link]());
} catch (Exception e) {
[Link]("Unexpected error: " + [Link]());
}
[Link]();
}
}
OUTPUT: Enter filename: ABCD
Error: File not found - ABCD (The system cannot find the file specified)