|
-
Nov 2nd, 2005, 04:33 PM
#1
Thread Starter
Fanatic Member
Throwing Exceptions
Can i use the throws clause on a static method?
Here is my code, it has an error in it.
Code:
import java.util.ArrayList;
import java.util.Iterator;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
/**
* Store items
*
* @author Daniel Morgan [362724]
* @version 1.0
*/
public class Library
{
private static ArrayList theItems;
/**
* Create a library
*/
public Library()
{
//ArrayList that will store all the new items
theItems = new ArrayList();
}
/**
* Run from command line
*/
public static void main()
{
//Create a new library
Library newLib = new Library();
//Start command interface
retrieveInput();
}
/**
* Create a new item and add it to the library arraylist
*
* @param Name The name of the item
* @param cost The cost of the item
*/
public static void createItem(String Name, int cost)
{
//Create a new instance of an item
Item newItem = new Item(Name, cost);
//Add it to the array list
theItems.add(newItem);
}
/**
* Print all items in the library
*/
public static void printAll()
{
//Create an iterator
Iterator itCount = theItems.iterator();
//Loop through all items in the library
while(itCount.hasNext())
{
Item currentItem = (Item)itCount.next();
//Print the item details
currentItem.print();
}
}
/**
* Retrieve the user input and provide the command interface
*
* @throws IOException
*/
public static void retrieveInput() throws IOException
{
//The input reader
BufferedReader usrInput = new BufferedReader(new InputStreamReader(System.in));
//'Name' and 'Cost' variables
String itemName = "";
String inputAnswer= "";
int itemCost = 0;
Boolean contInput = true;
while(contInput = true)
{
//Prompt user to create a new item
System.out.println("Do you want to create an item? (Yes or No)"); System.out.println("> ");
//Read input
inputAnswer = usrInput.readLine();
//Check input
if(inputAnswer.toLowerCase().equals("yes"))
{
//Prompt user for item 'Name'
System.out.println("Item name?"); System.out.println("> ");
//Read input
itemName = usrInput.readLine();
//Prompt user for item 'Cost'
System.out.println("Item Cost?"); System.out.println("> ");
itemCost = Integer.parseInt(usrInput.readLine());
//Create the item
createItem(itemName, itemCost);
//Notify user of success
System.out.println("Item created successfully");
//Print a blank line, for presentation purposes
System.out.println();
}//End If
//Prompt the user to print all items
System.out.println("Do you want to print all items? (Yes or No)"); System.out.println("> ");
//Read input
inputAnswer = usrInput.readLine();
//Check input
if(inputAnswer.toLowerCase().equals("yes"))
{
//Print all items
printAll();
//Print a blank line, for presentation purposes
System.out.println();
}//End If
//Repeater
System.out.println("Repeat this process? (Yes or No)"); System.out.println("> ");
//Read input
inputAnswer = usrInput.readLine();
//Check input
if(inputAnswer.toLowerCase().equals("yes"))
{
//Set continue flag
contInput = true;
}
else
{
//Set continue flag
contInput = false;
}//End If
}//End While
}
}
The error is in the line highlighted in bold. The error is:
Unreported exception java.io.IOException; must be caught or declared to be thrown.
Last edited by x-ice; Feb 25th, 2007 at 07:21 PM.
-
Nov 2nd, 2005, 04:35 PM
#2
Thread Starter
Fanatic Member
Re: Throwing Exceptions
Ok i have just done a little test and the error is gone. (Change my main() method to)
Code:
/**
* Run from command line
*/
public static void main() throws IOException
{
//Create a new library
Library newLib = new Library();
//Start command interface
retrieveInput();
}
I don't understand why though, the exception would be in the method retrieveInput() and not in the main() method so why would i need to throw or catch an exception in a method where it will never occur?
-
Nov 3rd, 2005, 01:14 AM
#3
New Member
Re: Throwing Exceptions
The error says you must either catch the IOException or declare that it will be thrown. The reason? It promotes good error handling; certrain exceptions - such as the NumberFormatException are runtime exceptions, as you cannot know whether a runtime exception will be thrown until the program runs you do not need to catch declare them as thrown.
Now put a catch statement in your retrieveNumber() function and you won't need to notify the main method of IOException:
Code:
public static void retrieveInput()
//The input reader
BufferedReader usrInput = new BufferedReader(new InputStreamReader(System.in));
//'Name' and 'Cost' variables
String itemName = "";
String inputAnswer= "";
int itemCost = 0;
Boolean contInput = true;
while(contInput = true)
{
//Prompt user to create a new item
System.out.println("Do you want to create an item? (Yes or No)"); System.out.println("> ");
//Read input
try {
inputAnswer = usrInput.readLine();
} catch (IOException e) {
System.out.println("Input/Output Error");
return;
}
....
And any other statement which uses userInput.readLine(). It may be better however, use the catch in the main function. 
Merry Christmas
I am the real Santa Clause 
-
Nov 6th, 2005, 05:39 AM
#4
Re: Throwing Exceptions
certrain exceptions - such as the NumberFormatException are runtime exceptions, as you cannot know whether a runtime exception will be thrown until the program runs you do not need to catch declare them as thrown.
This part is not quite correct. Any exception that you already know at compile time will be thrown is a programming error, a bug, and should not appear at all.
The difference between RuntimeException-derived and plain Exception-derived classes (NumberFormatException is not a runtime exception, btw) is that with RuntimeExceptions, conceptually you can never even really know what MIGHT throw them. NullPointerException, for example, might theoretically be thrown by every single object access. But the compiler is incapable of telling which accesses have the potential of throwing. A NumberFormatException, on the other hand, can only occur on the very specific action of parsing a string for a number.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Nov 6th, 2005, 08:19 AM
#5
New Member
Re: Throwing Exceptions
So, why does the NumberFormat exception not have be cautght declared as thrown, whereas exceptions such as IOException do?
I am the real Santa Clause 
-
Nov 6th, 2005, 09:24 AM
#6
Re: Throwing Exceptions
My mistake. Apparently it is a runtime exception.
Strange. I could have sworn it complains for me ...
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Nov 6th, 2005, 09:53 AM
#7
Frenzied Member
Re: Throwing Exceptions
This compiled fine, but when ran gave the numberformatexception. I truthfully would have expected that to be caught by the compiler.
Code:
class Test
{
public static void main(String[] args)
{
String s = "s1";
int x = Integer.parseInt(s);
}
}
-
Nov 7th, 2005, 01:31 AM
#8
New Member
Re: Throwing Exceptions
I guess other functions can throw the NumberFormat exception too and alos, it can be dependant on user input, whether or not that has any baring on whether it should be a runtime exception or not.
Can you have global exception handler in Java, which catches any excceptions which haven't been caught? I suppose you could put one in the main function like:
Code:
class Test
{
public static void main(String[] args)
{
try {
restOfProgram();
} catch (Exception e) {
/* do stuff */
}
}
}
Is it even a good idea to catch all exceptions?
I am the real Santa Clause 
-
Nov 7th, 2005, 03:25 AM
#9
Re: Throwing Exceptions
Well, considering that the runtime does pretty much the same as whatever you might do in the handler in main(), it's not very useful.
However, there are situations where you want to catch everything, just to keep the program running. The AWT event loop, for example, catches everything.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Nov 7th, 2005, 06:12 AM
#10
Frenzied Member
Re: Throwing Exceptions
I'd say if you're going to catch all, at least provide one or two specific exceptions:
Code:
try
{
someFunction();
}
catch(FileNotFoundException fnfe)
{
}
catch(IOException ioe)
{
}
catch(Exception e)
{
}
That's just my opinion though.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|