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

Java Exception Handling Exercises

The document contains instructions for three programming exercises. The first asks students to modify a program that counts letters in a word to handle non-letter characters by catching exceptions without errors. The second asks students to modify a program that sums integers in a string to skip non-integers by catching exceptions within a loop. The third asks students to modify a factorial program to throw exceptions for invalid input instead of returning incorrect results.

Uploaded by

quý nguyễn
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)
6 views4 pages

Java Exception Handling Exercises

The document contains instructions for three programming exercises. The first asks students to modify a program that counts letters in a word to handle non-letter characters by catching exceptions without errors. The second asks students to modify a program that sums integers in a string to skip non-integers by catching exceptions within a loop. The third asks students to modify a factorial program to throw exceptions for invalid input instead of returning incorrect results.

Uploaded by

quý nguyễn
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

Programming 2

Tutorial 9

Exercise 1: (Required)

File [Link] contains a program that reads a word from the user
and prints the number of occurrences of each letter in the word. Save it to your
directory and study it, then compile and run it to see how it works. In reading the
code, note that the word is converted to all upper case first, then each letter is
translated to a number in the range 0..25 (by subtracting 'A') for use as an index.
No test is done to ensure that the characters are in fact letters.

1. Run CountLetters and enter a phrase, that is, more than one word with spaces
or other punctuation in between. It should throw an
ArrayIndexOutOfBoundsException, because a non-letter will generate an
index that is not between 0 and 25. It might be desirable to allow non-letter
characters, but not count them. Of course, you could explicitly test the value of
the character to see if it is between 'A' and 'Z'. However, an alternative is to go
ahead and use the translated character as an index, and catch an
ArrayIndexOutOfBoundsException if it occurs. Since you want don't want to
do anything when a non-letter occurs, the handler will be empty. Modify this
method to do this as follows:

• Put the body of the first for loop in a try.


• Add a catch that catches the exception, but don't do anything with it.
• Compile and run your program.

2. Now modify the body of the catch so that it prints a useful message (e.g., "Not
a letter") followed by the exception. Compile and run the program. Although it's
useful to print the exception for debugging, when you're trying to smoothly
handle a condition that you don't consider erroneous you often don't want to. In
your print statement, replace the exception with the character that created the out
of bounds index. Run the program again; much nicer!

Exercise 2: (Required):

File [Link] contains a program that does the following:

1. Prompts for and reads in a line of input


2. Uses a second Scanner to take the input line one token at a time and parses
an integer from each token as it is extracted.
3. Sums the integers.
4. Prints the sum.
Save ParseInts to your directory and compile and run it. If you give it the
input

10 20 30 40

it should print

The sum of the integers on the line is 100.

Try some other inputs as well. Now try a line that contains both integers and
other values, e.g.,

We have 2 dogs and 1 cat.

You should get a NumberFormatException when it tries to call


[Link] on "We", which is not an integer. One way around this is
to put the loop that reads inside a try and catch the NumberFormatException but
not do anything with it. This way if it's not an integer it doesn't cause an error;
it goes to the exception handler, which does nothing. Do this as follows:
✓ Modify the program to add a try statement that encompasses the
entire while loop. The try and opening { should go before the while,
and the catch after the loop body. Catch a
NumberFormatException and have an empty body for the
✓ catch.
✓ Compile and run the program and enter a line with mixed integers
and other values. You should find that it stops summing at the first
non-integer, so the line above will produce a sum of 0, and the line
"1 fish 2 fish" will produce a sum of 1. This is because the entire
loop is inside the try, so when an exception is thrown the loop is
terminated. To make it continue, move the try and catch inside the
loop. Now when an exception is thrown, the next statement is the
next iteration of the loop, so the entire line is processed. The dogs-
and-cats input should now give a sum of 3, as should the fish input.

Exercise 3: (Required):

File [Link] contains a program utilizing the factorial method


from the MathUtils class to compute factorials of user-input integers. Save the
files to your directory, study the code, compile, and run Factorials to observe
its functionality. Test with various positive integers, then try a negative number.
You'll find it works for small positive integers (< 17), but returns a large negative
value for larger integers and 1 for negative integers.

1. Correcting the behavior for negative integers:


Modify the factorial method header to declare that it can throw an
IllegalArgumentException.
Adjust the factorial method body to throw an
IllegalArgumentException if the argument is negative. Pass a
specific message to the constructor indicating the issue.
Compile and run Factorials to observe the program throwing an
exception for negative numbers.
2. Correcting the behavior for values over 16:
Enhance the factorial method to also check for arguments over 16,
signaling an IllegalArgumentException. Provide distinct messages
for both negative and large arguments to clarify the issue.

Common questions

Powered by AI

Exception handling strategies can be adapted to improve user experiences in interactive applications by providing user-friendly feedback and ensuring continuous operation. By catching exceptions and replacing technical error messages with comprehensible alerts or suggestions, users can be guided to correct issues effortlessly. Implementing recovery mechanisms that allow applications to maintain functionality despite errors can reduce user frustration. Furthermore, integrating logging can help developers refine user interactions by analyzing exception causes without interrupting user tasks. Enhancing feedback loops, maintaining task continuity, and offering meaningful guidance through thoughtful exception handling can significantly bolster user satisfaction.

In CountLetters.java, the strategy involves using an empty catch block to ignore ArrayIndexOutOfBoundsExceptions that result from non-letter inputs, allowing the program to skip over these characters without interruption. This approach doesn’t act upon the exceptions other than to bypass erroneous inputs. In ParseInts.java, the initial strategy involves enclosing the whole loop in a try block, which leads to termination upon the first exception; however, adjusting it to place the try-catch inside the loop allows for each non-integer token to be handled individually, ensuring that processing continues. Both strategies focus on maintaining execution flow, but implement it in contextually unique ways to cater to specific input processing requirements.

Exception handling with try-catch blocks significantly affects program control flow by allowing deviations from the normal execution path when exceptions occur. Rather than terminating the program or yielding erroneous results, a try-catch structure redirects control flow to the catch block, where the exception can be managed accordingly. This mechanism provides a structured way to handle unforeseen conditions, maintaining stability and allowing for recovery actions, such as continuing execution or cleaning up resources, without crashing. Compared to linear execution, exception handling introduces complexity by integrating possible branching flow paths based on runtime conditions.

Not validating inputs in programs like CountLetters can lead to exceptions such as ArrayIndexOutOfBoundsException for non-letter characters, disrupting execution unexpectedly. In Factorials, the lack of validation for arguments can result in returning incorrect factorial values, such as negative results for large numbers. These issues can be mitigated by implementing robust input validation measures such as checking character types and range bounds, using appropriate exceptions with user-friendly messages to provide feedback, and ensuring that all potential erroneous inputs are accounted for within the program design to maintain proper functionality.

Modifying the factorial method to throw an IllegalArgumentException for negative integers and numbers greater than 16 is significant for input validation. It ensures that invalid input scenarios are handled gracefully and prevents undefined or erroneous outputs, such as returning a 1 for negative integers or large negative values for numbers greater than 16. This approach provides a clear feedback mechanism to the user by signaling what constitutes invalid input with specific messages.

To handle mixed strings and integers effectively in the ParseInts program, move the try-catch block inside the while loop so that each token is individually processed. This allows the loop to continue iterating over the tokens even if a NumberFormatException is thrown, because after catching an exception for a non-integer token, the loop does not terminate but instead proceeds to the next token. This adjustment ensures that all integers in the input line are correctly summed, regardless of non-integer interruptions.

To handle non-letter characters without throwing an exception in the CountLetters program, you should use a try-catch block. Place the body of the first for loop inside a try block and catch an ArrayIndexOutOfBoundsException if it occurs. Instead of performing any actions inside the catch block, simply leave it empty, which allows the program to ignore non-letter characters and continue running. This way, the program won’t terminate unexpectedly when encountering non-letter inputs.

Enclosing the entire while loop inside a try block in ParseInts.java causes the loop to terminate immediately upon encountering an exception because when a NumberFormatException is thrown, the control flow jumps out of the loop to the catch block, and doesn’t return to continue processing subsequent tokens. As a result, no further integers are summed after the first non-integer.

Modifying the catch block in CountLetters.java to display a message such as 'Not a letter' followed by the offending character enhances usability by providing immediate feedback to the user regarding the nature of the ignored input. This improvement allows users to understand why certain inputs are not processed and can help in debugging and revising their input more effectively. Clear communication of what triggers exceptions enhances the overall user experience and program reliability.

The rationale for throwing specific exceptions with detailed messages in Java programs, such as in Factorials, is to provide clear and precise information about errors when invalid conditions are encountered. By signaling specific issues, such as negative input values or values exceeding a predefined threshold, the program can not only prevent incorrect operations but also alert users to the exact nature of the problem. This practice supports effective debugging and enhances code maintainability by allowing developers and users to quickly understand and address the reasons prompting exceptions.

You might also like