select a Java program of your choice which contain an exception error. Explain a
ID: 3851721 • Letter: S
Question
select a Java program of your choice which contain an exception error. Explain at what conditions such an error might occur when the program runs and its potential implications. Then explain how you can handle such an exception making use of Java Exception Handling technique. Along with your comments and explanations - please do not forget to include the actual Java code ( it is not necessary to post the completed application or long Java codes - the proper code fragments, illustrating your exception handling routines will do).
Explanation / Answer
Below is the answer for your question. Please don't forget to rate the answer if it helped. Thank you very much.
Example of Java Exception:
1 ) Consider an example of opening for reading a file and displaying its contents.
We can ask user to specify a file name and try opening it. It is possible at times
that the file does not exist in the system. In such a case, trying to open the file
will throw an exception. Using Java's exception handling we can gracefully handle
such a scenario by displaying an error message to the user and asking for a
different filename.
2)Another example of exception - If we want a user to input a number and want to validate
that he indeed entered a number, we can use exception handling here.
First we can get user's input as a string and then use Integer.parseInt()
method to convert the string to an int. This method throws an exception if the string is
not numeric.
The following code illustrates the above examples of exception handling in Java.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String filename ;
//illustrate FileNotFoundException when file is not found
while(true)
{
//asks user for a file name to be opened
System.out.println("Enter a filename to open: ");
filename = keyboard.next();
//try to open the file specified by user
try {
Scanner s = new Scanner(new File(filename));
while(s.hasNextLine())
System.out.println(s.nextLine());
s.close();
break;
} catch (FileNotFoundException e) { //Handle the scenario when file does not exist
System.out.println("Error opening file " + filename);
System.out.println("Try with another file.");
}
}
//illustrate NumberFormatException
System.out.println("Enter your age: "); //ask user for numeric input
String input = keyboard.next();
try
{
int age = Integer.parseInt(input); //try to convert string to int
System.out.println("You are " + age + " years old.");
}catch(NumberFormatException e) //exception thrown if the string is not numeric
{
System.out.println("You did not enter an integer !");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.