0% found this document useful (0 votes)
16 views1 page

Java Exception Handling Examples

Uploaded by

aj.ajay02nd
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)
16 views1 page

Java Exception Handling Examples

Uploaded by

aj.ajay02nd
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

1.

Write a Java program to create a method that takes an integer as a


parameter and throws an exception if the number is odd.
2. Write a Java program to create a method that reads a file and throws
an exception if the file is not found.

3. Write a Java program that reads a list of integers from the user and
throws an exception if any numbers are duplicates.

4. Create a simple banking application where users can withdraw


money from their accounts. Implement a method withdraw that
takes an amount to withdraw and the account balance. If the amount
to withdraw is greater than the balance, throw a custom exception
called InsufficientFundsException. Handle this exception in the main
method and print an appropriate message.

5. Implement a method convertToCelsius that takes a temperature in


Fahrenheit and converts it to Celsius. If the input is not a valid
number, throw a custom exception called
InvalidTemperatureException. Handle this exception in the main
method and print an appropriate message.

6. Create a Java program that performs the following tasks: (for array of
size 5)

a) Prompt the user to enter a number.


b) Calculate the square root of the number.
c) Store the result in an array of doubles.
d) Allow the user to retrieve the stored result by entering the
index.
e) Handle potential exceptions such as:
a. Non-numeric input
b. Negative numbers (for square root)
c. Array index out of bounds

Common questions

Powered by AI

When reading user input for numerical operations like calculating square roots, check input types and values thoroughly. Employ try-catch blocks to handle exceptions such as `InputMismatchException` for non-numeric inputs. For negative numbers, throw `IllegalArgumentException` as square roots of negatives cannot be computed with real numbers. Finally, validate access to result storage through bounds checking to prevent `ArrayIndexOutOfBoundsException`. This comprehensive error management ensures robust and user-friendly interaction.

To handle odd integers in a Java method, you would design the method to accept an integer parameter and use an 'if' statement to check if the number is odd using modulus 2 (`number % 2 != 0`). If the number is odd, you should throw a custom exception, for instance, `OddNumberException`. This involves creating a custom exception class that extends `Exception`. In a main method or caller context, use a try-catch block to catch this exception type and handle it appropriately by printing a relevant message. This strategy effectively isolates and manages unexpected or undesirable input while allowing the program to continue execution.

The withdrawal function in a banking application should accept the withdrawal amount and check against the account balance. If the amount exceeds the balance, throw a custom exception, `InsufficientFundsException`. Create the exception class by extending `Exception` and implement a meaningful error message. In the main method, wrap the withdrawal attempt in a try-catch block, handling the `InsufficientFundsException` by informing the user they cannot withdraw more than their balance, ensuring clarity in user communication and protecting account integrity.

To detect duplicate integers from user input, store integers in a data structure that checks for duplicates efficiently, like `HashSet`. As integers are entered, attempt to add them to the `HashSet`. If adding fails due to a duplicate entry (using `Set`'s property of rejecting duplicates), throw a custom exception, e.g., `DuplicateNumberException`. Inside the main method, use a try-catch block to capture this exception and inform the user of duplicate entries. This leverages the Java Collection Framework and exception handling for effective user input validation.

To ensure robust exception handling when reading files in Java, use a method that opens the file using `FileReader` or `FileInputStream` within a try block. Java provides `FileNotFoundException`, a subclass of `IOException`, which can be thrown if the file does not exist. Implement a catch block for `FileNotFoundException` to handle the error gracefully, e.g., by printing an error message indicating the file was not found or prompting the user to check the file path. Additionally, utilizing a `finally` block to close resources like file streams can prevent resource leaks.

Designing a temperature conversion program involves implementing a method `convertToCelsius` that accepts a Fahrenheit temperature input and checks its validity before processing. If the input is not numeric, throw a custom exception, `InvalidTemperatureException`. This exception should be handled in the main method using a try-catch block, where invalid inputs trigger a user-friendly message prompt, ensuring informative feedback is provided to the user without crashing the program. This approach integrates input validation and exception handling to manage erroneous inputs effectively.

You might also like