0% found this document useful (0 votes)
0 views11 pages

CH - 4 - Lab Exercise

The document provides several Java exercises focused on exception handling, including using try-catch blocks for division, array access, file reading, and custom exceptions. Each exercise includes a problem statement, solution code, and explanations of key concepts such as specific exceptions and the use of finally blocks. The exercises demonstrate how to effectively manage errors and improve code robustness in Java applications.

Uploaded by

ermiasa067
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)
0 views11 pages

CH - 4 - Lab Exercise

The document provides several Java exercises focused on exception handling, including using try-catch blocks for division, array access, file reading, and custom exceptions. Each exercise includes a problem statement, solution code, and explanations of key concepts such as specific exceptions and the use of finally blocks. The exercises demonstrate how to effectively manage errors and improve code robustness in Java applications.

Uploaded by

ermiasa067
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/ 11

Here's a simple exercise to practice using try-catch blocks in Java:

Problem:
Write a Java program that asks the user to enter two numbers and then divides the first number
by the second. Handle the following exceptions:
 If the user enters a non-numeric value, catch it and display an error message.
 If the user tries to divide by zero, catch the ArithmeticException and display a relevant
message.
 If any other unexpected error occurs, catch it and display a general error message.
Solution:
Explanation:
 try block: Contains the code that may throw exceptions. In this case, parsing input and
performing division.
 catch blocks: Handle specific types of exceptions.
o NumberFormatException: This exception is thrown if the user enters a non-
numeric input (e.g., a string).
ArithmeticException: This exception is thrown when an arithmetic error occurs, such as dividing
by zero.
import java.util.Scanner;

public class DivisionWithExceptionHandling {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
// Ask for user input
System.out.print("Enter the first number: ");
int num1 = Integer.parseInt(scanner.nextLine());

System.out.print("Enter the second number: ");


int num2 = Integer.parseInt(scanner.nextLine());
// Perform division
int result = num1 / num2;
System.out.println("Result: " + result);
}
catch (NumberFormatException e) {
System.out.println("Error: Please enter valid numbers.");
}
catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
finally {
// Close the scanner resource
scanner.close();
}
}
}
Exception: A general catch block that catches any unexpected exceptions.
 finally block: This block will always execute, regardless of whether an exception was
thrown or not. In this case, we use it to close the Scanner to free up resources.
Example Output:
Case 1: Valid input
Enter the first number: 10
Enter the second number: 2
Result: 5
Case 2: Division by zero
Enter the first number: 10
Enter the second number: 0
Error: Cannot divide by zero.
Case 3: Invalid input
Enter the first number: abc
Error: Please enter valid numbers.
This exercise demonstrates how to handle specific exceptions in Java using the try-catch
mechanism. Let me know if you'd like to explore other variations of exception handling!
2. Here's an exercise where we can practice handling the ArrayIndexOutOfBoundsException
using try-catch blocks in Java.
Problem:
Write a Java program that:
1. Creates an array of integers with a fixed size.
2. Prompts the user to enter an index to retrieve an element from the array.
3. Catches the ArrayIndexOutOfBoundsException if the user tries to access an index that is
out of bounds.
4. Displays a custom error message when this exception occurs.
Solution:
import java.util.Scanner
public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
// Creating an array of integers with 5 elements
int[] numbers = {10, 20, 30, 40, 50};

Scanner scanner = new Scanner(System.in);

try {
// Ask the user to enter an index
System.out.print("Enter an index (0-4) to access an element in the array: ");
int index = Integer.parseInt(scanner.nextLine());

// Try to access the element at the given index


System.out.println("Element at index " + index + ": " + numbers[index]);
}
catch (ArrayIndexOutOfBoundsException e) {
// Catch the ArrayIndexOutOfBoundsException and print an error message
System.out.println("Error: Index out of bounds! Please enter a valid index between 0 and
4.");
}
catch (NumberFormatException e) {
// Catch invalid input (non-integer)
System.out.println("Error: Please enter a valid integer for the index.");
}
finally {
// Close the scanner resource
scanner.close();
}
}
}
Explanation:
1. Array Initialization: The program initializes an array of integers with 5 elements ({10,
20, 30, 40, 50}).
2. User Input: The user is prompted to enter an index (between 0 and 4) to access an
element in the array.
3. Try-Catch Block:
o ArrayIndexOutOfBoundsException: If the user enters an index outside the
bounds of the array (i.e., any number less than 0 or greater than 4), this exception
is thrown, and the program catches it to display an appropriate error message.
o NumberFormatException: If the user enters something that's not a number (like
a string), this exception is caught to display a message prompting the user to enter
a valid number.
4. Finally Block: The finally block ensures that the Scanner resource is closed at the end,
whether an exception occurred or not.
Example Output:
Case 1: Valid index
Enter an index (0-4) to access an element in the array: 2
Element at index 2: 30
Case 2: Index out of bounds
Enter an index (0-4) to access an element in the array: 10
Error: Index out of bounds! Please enter a valid index between 0 and 4.
Case 3: Invalid input (non-integer)
Enter an index (0-4) to access an element in the array: abc
Error: Please enter a valid integer for the index.
This exercise demonstrates how to handle exceptions when working with arrays in Java,
specifically catching out-of-bound errors using ArrayIndexOutOfBoundsException. Let me
know if you'd like more examples or further details!
Great! Here's an exercise where we can practice handling the FileNotFoundException using try-
catch blocks in Java.
Problem:
Write a Java program that:
1. Tries to read from a file specified by the user.
2. If the file doesn't exist or the path is incorrect, catch the FileNotFoundException and
display a custom error message.
3. If any other error occurs during file reading, handle it using a general IOException catch
block.
4. Ensure the file reading resource is closed after reading using the finally block.
Solution:
import java.io.*;

public class FileNotFoundExample {


public static void main(String[] args) {
// Ask the user for the file path
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {
System.out.print("Enter the path of the file to read: ");
String filePath = reader.readLine();

// Create a File object


File file = new File(filePath);

// Try to read the file


BufferedReader fileReader = new BufferedReader(new FileReader(file));
String line;
System.out.println("Reading the content of the file:");

// Read and print each line of the file


while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}

fileReader.close(); // Close the file reader


}
catch (FileNotFoundException e) {
// Handle file not found exception
System.out.println("Error: The file at the specified path does not exist.");
}
catch (IOException e) {
// Handle general IO exceptions
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
finally {
try {
// Close the BufferedReader to avoid resource leaks
reader.close();
} catch (IOException e) {
System.out.println("Error closing the input reader.");
}
}
}
}
Explanation:
1. User Input: The program prompts the user to enter the file path they want to read.
2. File Handling:
o BufferedReader and FileReader are used to read the file.
o A File object is created from the user-provided path, and the program attempts to
open and read from this file.
3. Try-Catch Block:
o FileNotFoundException: This exception is thrown when the file does not exist at
the specified location. If this happens, a friendly error message is displayed to the
user.
o IOException: A general I/O exception that might occur during reading or closing
the file is caught and handled.
4. Finally Block: In the finally block, we ensure that the BufferedReader used to take the
file path input is closed, even if an exception occurs.
Example Output:
Case 1: File found and successfully read
If the file sample.txt exists and contains some text:
Enter the path of the file to read: sample.txt
Reading the content of the file:
This is the first line.
This is the second line.
This is the third line.
Case 2: File not found
If the user enters a non-existent file path:
Enter the path of the file to read: non_existent_file.txt
Error: The file at the specified path does not exist.
Case 3: General I/O error
If there's an error while reading the file (e.g., the file is not readable due to permission issues):
Enter the path of the file to read: protected_file.txt
An error occurred while reading the file: protected_file.txt (Permission denied)
Key Concepts:
 FileNotFoundException: This is a subclass of IOException, specifically used when the
file being accessed cannot be found.
 IOException: A more general exception that covers various types of input/output errors,
including file reading issues.
 Finally Block: Ensures that resources (like BufferedReader) are properly closed, even if
an exception occurs.
This exercise helps you practice handling FileNotFoundException and other potential IO
exceptions that could occur when reading files in Java. Let me know if you'd like more examples
or details!
Let's dive into a lab exercise that demonstrates the usage of the throw and throws keywords in
Java.
Problem:
Write a Java program that:
1. Defines a method checkAge(int age) that checks if the age is above 18.
2. If the age is below 18, throw an exception using the throw keyword with a custom
exception.
3. Define the custom exception class AgeException to be thrown when the age is not valid.
4. The main method calls checkAge and handles the exception using the throws keyword.
Concept of throw and throws:
 throw is used to explicitly throw an exception from a method or a block of code.
 throws is used in a method signature to declare that the method might throw certain
exceptions, so the caller is aware of the exception handling responsibility.
Solution:
Step 1: Create the custom exception class AgeException.
// Custom exception class
public class AgeException extends Exception {
public AgeException(String message) {
super(message); // Passing the message to the parent (Exception) class
}
}
Step 2: Create the checkAge method that uses throw to throw an exception.
// Main program
public class AgeValidation {

// Method that checks age and throws AgeException if age < 18


public static void checkAge(int age) throws AgeException {
if (age < 18) {
// Throwing the custom exception
throw new AgeException("Age is below 18! Access denied.");
} else {
System.out.println("Age is valid. Access granted.");
}
}

public static void main(String[] args) {


try {
// Test with age input
int age = 15; // You can change this value to test different scenarios
checkAge(age); // Calling checkAge method
}
catch (AgeException e) {
// Handling the custom exception
System.out.println("Caught exception: " + e.getMessage());
}
}
}
Explanation:
1. Custom Exception (AgeException):
o This class extends the Exception class, making it a checked exception. It allows
us to create a custom exception with a meaningful message.
2. Method (checkAge):
o The method checkAge(int age) is designed to check if the input age is below 18.
If so, it throws an AgeException.
o The method signature includes throws AgeException, which means this method is
declaring that it might throw AgeException, so it must be handled by the caller
(using try-catch).
3. Main Method:
o The main method tries to call checkAge(15) with an age of 15, which is less than
18, so it will throw an exception. The exception is caught in the catch block and a
message is displayed.
4. throw Keyword:
o The throw keyword is used inside the checkAge method to throw the custom
exception (AgeException) if the age is below 18.
5. throws Keyword:
o The throws keyword in the method signature of checkAge(int age) indicates that
this method may throw AgeException, and the caller (in this case, the main
method) is responsible for handling it.
Example Output:
Case 1: Age is below 18
Caught exception: Age is below 18! Access denied.
Case 2: Age is 18 or above
If the age is above 18 (e.g., age = 20), the output will be:
Age is valid. Access granted.
Key Concepts:
 throw: The throw keyword is used to explicitly throw an exception. In this case, we are
throwing an instance of the AgeException if the age is less than 18.
 throws: The throws keyword is used in the method signature to declare that the method
might throw a certain type of exception. This forces the caller to handle or propagate the
exception.
 Custom Exceptions: Creating custom exceptions like AgeException helps in improving
the clarity and maintainability of the code by providing specific exception messages.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy