Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Throwing Exceptions Back to Main Method

$
0
0
Hello everyone I have a question I cant seem to find an answer for. I am reading a file and my assignment requires I handle a few different exceptions. Now it says that error messages must only print from the main method, so the exceptions must be thrown back to the main method to be printed. The parts I cannot figure out is how to determine where in the file the error occurs and how to throw the information back to the main. Here is the main method which asks the user to enter the name of files and catches errors if they occur.

public static void main(String[] args) throws IOException
	{
		Scanner in = new Scanner(System.in);
		System.out.println("Enter the name for the univerals list of items");
		ItemList listOne = new ItemList();
		try
		{
			listOne.fillItemList(in.next());
		}
		catch (FileNotFoundException fnfe)
		{
			System.out.println("The file you entered does not exist. Enter a new name");
			listOne.fillItemList(in.next());
		}
		catch (ArrayIndexOutOfBoundsException aioobe)
		{
			System.out.println("The universal list file was not formatted correctly\nThere seems to be a problem with line(need to find out how to determine line)");
			System.out.println("This error was caused by " + aioobe.getClass());
		}


Here is a method in a class that takes a fileName and reads in each line and adds the information to an ArrayList<>

public void fillItemList(String fileName) throws IOException
	{
		File fileOne = new File(fileName);
		Scanner fileReader = new Scanner(fileOne);
		while (fileReader.hasNextLine())
		{
			String[] line = fileReader.nextLine().split(" ");// for items with three names
			if (line.length == 4)
			{
				String name = line[0] + " " + line[1] + " " + line[2];
				String upc = line[3];
				listOfItems.add(new Item (name, upc));
			}			
			if (line.length == 3)// for items with two names
			{
				String name = line[0] + " " + line[1];
				String upc = line[2];
				listOfItems.add(new Item (name, upc));
			}
			else //(line.length == 2)
			{
				listOfItems.add(new Item(line[0], line[1]));
			}
			
		}
	}


I am unsure how to get the information from an exception from the non main class to the main class. Do I need try/catch blocks in the non main class and throw the info back to the main or are they required in both. Also when reading the file I am required to report at what line in the file the error occurs. I was guessing having an int and adding one every time the while loop ran and reporting that if an exception occurs, but again i'm not sure how to report this information back to the main method.

Thanks in advance
Alex

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>