I'm trying to write my first ever java program. I don't know how to read in an int for example or a string. I'm a C++ programmer, and just now starting Java, that's my background. Here is what I already have:
And here is the error I get when I'm compiling:
prog4.java:38: unreported exception java.io.IOException; must be caught or declared to be thrown line = in.readLine(); ^ 1 error
Any ideas? I tried using exception but I got the same error. What am I missing? Thanks
I guess you get a first error, when trying to omit 'System' in 'System.out'.
And you needn't import java.lang - it's automatically imported every time.
To your question: Exceptions are thrown, when an error occurs, and the Library doesn't know how to handle it. Maybe you can handle it. If yes, catch it, and handle it. If no, declare your method to throw it, so your caller might catch it.
Since we don't have a caller, we are on our own. If System.in is in an errorstate, there isn't much what we can do. But reporting the error is what we should do at least:
If the user inputs invalid stuff like "fourtytwo", the next exception occurs. Here you have much better possibilities to react, if you try and catch the NumberFormatException: ask again for input.
In your program it isn't of much help, but in a complex program terminating on such an error is unfriendly.