If anyone culd help?? I'm getting this error: Ch2_Lab.java:53: unreported exception java.io.IOException; must be caught or declared to be thrown num = Integer.parseInt(keyboard.readLine()); ^ Ch2_Lab.java:57: unreported exception java.lang.Exception; must be caught or declared to be thrown throw new Exception("Exception: Number cannot be negative"); ^ 2 errors
You can only throw checked exceptions from a method if the method declares these exceptions, i.e. :
If you don't declare the method with "throws" you need to handle the exception within the method. This is because checked exceptions exist to allow the compiler to check that they are properly being handled. Basically the possibility the an operation can fail, and an indication of how it might fail is written into the language to force the coder to handle this possibility. [ January 25, 2007: Message edited by: Paul Sturrock ]
You are not catching the exceptions being thrown. keyboard.readLine() throws IOException, and you throw just a plain Exception. Then the only catch you consider is a NumberFormatException, though this is never thrown. So all you need is to make sure you catch IOException AND catch Exception (or throw a NumberFormatException instead).