0% found this document useful (0 votes)
5 views4 pages

Java Exception Handling Lab Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Java Exception Handling Lab Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA EXCEPTION HANDLING LAB

Q1. Create a class named InputSafeCalculator. Implement a static method calculate


Ratio(String num1Str, String num2Str) that returns a String. Inside the method, use a single
try block to:

 Convert num1Str and num2Str to integers using [Link]().

 Calculate the integer division of the first number by the second.

 Return the result as a String.

Implement a multi-catch block to handle both NumberFormatException (if [Link]()


fails) and ArithmeticException (if the divisor is 0). In the catch block, print an error message
specifying the type of error and return "Error: Invalid operation."Include a finally block that
prints: "Cleanup complete: Ratio calculation finished."In the main method, test the function
with:

 Valid input (e.g., "10", "2").

 NumberFormatException input (e.g., "ten", "2").

 ArithmeticException input (e.g., "10", "0").

SOL: package ExceptionHandlingLab;

import [Link];

public class InputSafeCalculator {

public static String calculateRatio(String num1Str, String num2Str) {

try {

int num1 = [Link](num1Str);

int num2 = [Link](num2Str);

int result = num1 / num2;

return [Link](result);

} catch (NumberFormatException | ArithmeticException e) {

[Link]("Error: " + [Link]().getSimpleName() + " - " + [Link]());

return "Error: Invalid operation.";

} finally {

[Link]("Cleanup complete: Ratio calculation finished.");

}
}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter first number: ");

String input1 = [Link]();

[Link]("Enter second number: ");

String input2 = [Link]();

String result = calculateRatio(input1, input2);

[Link]("Result: " + result);

[Link]();

OUTPUTS:

a) Enter first number: 10

Enter second number: 2

Cleanup complete: Ratio calculation finished.

Result: 5

b) Enter first number: ten

Enter second number: 2

Error: NumberFormatException - For input string: "ten"

Cleanup complete: Ratio calculation finished.

Result: Error: Invalid operation.

c) Enter first number: 10

Enter second number: 0

Error: ArithmeticException - / by zero

Cleanup complete: Ratio calculation finished.

Result: Error: Invalid operation.


Q2. Create a class named SecurityManager.
Implement a static method checkPassword(String password):

 It must declare throws Exception in its signature.

 If the password is null or empty, use throw new Exception("Authentication failure:


Password cannot be empty.").

 If the password is valid, print "Password check successful."

Implement a static method processData(String password):

 It must call checkPassword(password).

 Wrap the call in a try-catch block to handle the declared Exception.

 If the Exception is caught, the method must print a log message

 If no exception occurs, print "Data successfully processed."

In the main method, call processData() twice:

once with a valid password ("secret"),

and once with an invalid password (null).

Wrap the calls in a try-catch block to catch

SOL: package ExceptionHandlingLab;

import [Link];

public class SecurityManager {

public static void checkPassword(String password) throws Exception {

if (password == null || [Link]()) {

throw new Exception("Authentication failure: Password cannot be empty.");

if (![Link]("secret")) {

throw new Exception("Authentication failure: Incorrect password.");

[Link]("Password check successful.");

}
public static void processData(String password) {

try {

checkPassword(password);

[Link]("Data successfully processed.");

} catch (Exception e) {

[Link]("Log: Exception caught in processData - " + [Link]());

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter password: ");

String inputPassword = [Link]();

processData(inputPassword);

[Link]();

OUTPUTS:

a) Enter password: secret

Password check successful.

Data successfully processed.

b) Enter password:

Log: Exception caught in processData - Authentication failure: Password cannot be empty.

Common questions

Powered by AI

Exception handling in the `calculateRatio` method uses a single try with a multi-catch block to address `NumberFormatException` and `ArithmeticException` and includes a `finally` block to signal cleanup completion. It focuses on mathematical operations and input parsing. In contrast, `processData` uses a try-catch to invoke `checkPassword` and capture the general exception it throws, focusing on security and input validity. Both methods offer user feedback, but `calculateRatio` emphasizes error types, while `processData` handles security exceptions.

Closing the `Scanner` object in the `main` methods of both classes is significant for resource management. It releases underlying resources tied to standard input, preventing resource leaks and potential memory issues. This practice is crucial for robust application development, especially when dealing with multiple or potentially large inputs, ensuring that resource consumption is minimized and efficiency is maintained in the application lifecycle.

Input validation in the `checkPassword` method is crucial for enforcing security. It checks if the password is null or empty, which could otherwise lead to logical errors or undefined behavior, throwing an exception with a message when validation fails. This preemptive check helps to prevent unauthorized access by ensuring that only valid passwords are considered for further processing. Additionally, verifying password correctness through equality checks further strengthens security by requiring an exact match with the correct password.

The use of a `finally` block in the `calculateRatio` method is effective because it ensures that certain clean-up actions occur, irrespective of whether an exception is thrown or not. This block prints "Cleanup complete: Ratio calculation finished," providing consistent feedback to signify the end of the calculation process and indicating resource cleanup, which is a good practice for maintaining predictable program behavior.

The try-catch block in the `processData` method handles exceptions by enclosing the method `checkPassword` invocation. If `checkPassword` throws an exception due to an authentication failure, the catch block captures it and logs an error message specifying that an exception was caught, along with the exception's message. This ensures that the program continues execution without crashing and provides useful information about the exception for debugging purposes.

The `calculateRatio` method involves a single try block where it attempts to convert the strings `num1Str` and `num2Str` to integers using `Integer.parseInt()`. It then attempts to perform an integer division of the first number by the second. A multi-catch block handles exceptions specifically `NumberFormatException` if parsing fails, and `ArithmeticException` if the divisor is zero. If an exception occurs, an error message is printed, stating the type of error, and the method returns "Error: Invalid operation." Finally, regardless of an exception, the block prints "Cleanup complete: Ratio calculation finished."

To ensure the `calculateRatio` method handles all potential user inputs effectively, create comprehensive test cases covering valid integers, invalid strings (e.g., "ten"), zero as a divisor, and edge cases like maximum integer values. Automated tests should assert correct handling of `NumberFormatException` and `ArithmeticException`, and verify that the `finally` block executes. Additionally, mock streams could test user interaction reinstatement after computation, ensuring a robust validation strategy.

The exception handling strategy in `SecurityManager` is effective in identifying authentication failures by throwing and catching exceptions when passwords are invalid or incorrect. However, a more specific exception type than `Exception` could improve clarity and maintenance by providing more context about authentication issues. Additionally, providing a mechanism to retry with valid input or log detailed security events could enhance the robustness and auditability of the system.

When `processData` is executed with a null password, `checkPassword` is invoked and throws an exception because the password is empty. The try-catch block in `processData` catches the exception, logs a message stating "Log: Exception caught in processData - Authentication failure: Password cannot be empty," and the program continues without halting unexpectedly. This structured handling provides informative feedback while maintaining flow control.

The multi-catch block in the `calculateRatio` method handles both `NumberFormatException` and `ArithmeticException` by catching any of these exceptions with a single catch statement. This approach simplifies the code and ensures that both types of exceptions are handled uniformly. When an exception occurs, it prints an error message including the exception type and message, improving debugging and user feedback, and it returns "Error: Invalid operation."

You might also like