954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How can I make a loop using an exception?

try {
dataFile = args[0];
}

catch (Exception e) {
System.out.println("The file was not found. Please input file name now: ");
dataFile = scan.nextLine();
}


This gets a file name from the command line, and if no file is specified it asks the user to input a file name, however, it only asks once. If no valid file name is inputted it produces an error message. What code should I use to loop this so it will repeatedly ask the user to input a file until he/she inputs a valid file name?

ferretfool0x77
Newbie Poster
4 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

On way to do it is to put the whole thing in a method. If it throws an exception, call the method again...

public void tryFile() {
  System.out.print("Enter file name: ");
  try { dataFile = scan.nextLine(); }  // assume that scan is the class variable
  catch (Exception e) {
    System.out.println("The file was not found. Please input file name now: ");
    tryFile();
  }
}
Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

Heeding your advice, I wrote this:

// start main method with necessary variables
try {
	dataFile = args[0];
}

catch (Exception e) {
	dataFile = fileNotFound();
}
// end of main method

public static String fileNotFound() {

	String fileName = "";
	Scanner scan = new Scanner(System.in);
	System.out.println("The file was not found. Please input file name now: ");

	try {
		fileName = scan.nextLine();
	} catch (Exception e) {
		fileNotFound();
	}

	return fileName;

	}


Yet, I still receive the FileNotFoundException after the first prompt.

ferretfool0x77
Newbie Poster
4 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

You would normally use a template something like this:

String fileName = "";
while (fileName.equals("")) {
   try {
      // get the file name - if successful fileName will not be ""
   } catch(...) {
      // do error message
      fileName = ""; // force it round the loop again
   }
}
JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

try - catch - finally up to Java6, in Java7 try - finally

mKorbel
Veteran Poster
1,141 posts since Feb 2011
Reputation Points: 480
Solved Threads: 224
 

The code you are trying is wrong ...

Try checking file exists if not ask the user to type the file name again .. it is very simple .. why you need to create an exception for this ?

skoiloth
Newbie Poster
8 posts since Oct 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: