OK, so in this specific example, absolutely any sequence of bytes can be a valid string. So when you read a string from the file-- I assume you're thinking of one "string" per line, so you'd generally use BufferedReader.readLine()-- Java can't predict that what you actually want is strings that fulfil a certain condition, e.g. strings that aren't also valid number representations. So in this specific case, you would have to specifically check for the strings not being integers, and "do something" in that case:
- if you throw an exception, you are generally (a) signalling to the PROGRAM that something has gone wrong, and (b) controlling error flow within your program -- generally terminating the "bit of program" that was running -- e.g. if you had a method that read the strings, you could make that method throw the exception;
- if you just print something out, this might be fine if you just want to warn the user of that particular failure, but it doesn't tell your program that something's gone wrong -- so unless you do something else, it'll just plough on regardless
Now, if you throw an ordinary checked exception, that means that you have to catch it somewhere. For example, the bit of program that calls your string-reading method could have a try/catch, and in the catch block, print out a message to the user. You might think, "why don't I just print the message when I detect the bad string", but the point is the exception allows you to control program flow: terminating the method, or possibly interrupting a whole chain of methods and passing the error "back up to the caller".
If the exception that you throw is some type of RuntimeException, then you don't have to catch it (though you can) -- if nothing catches it, then the thread (=your program -- I assume you're not doing multithreaded programming yet) will terminate, and Java's default exception handler will kick in, printing out the exception.
Now, on the other hand, there are cases where "the system" will automatically throw an exception:
- many library methods will throw exceptions in particular documented cases -- for example, file operations such as readLine() can throw IOException; if you were using Integer.parseInt() to turn a string into a number, it would throw NumberFormatException if the string wasn't a valid int; but that depends on the particular library call you're making and you need to check the documentation of the particular method in question
- as I mentioned in my previous post, there are a few "build-in" operations that can also throw (unchecked) exceptions: divide by zero, running out of memory, calling a method on a null object, trying to use a negative array index etc etc.
Last edited by neilcoffey; Dec 11th, 2008 at 11:29 pm. Reason: Forgot to add a bit