• Post Reply Bookmark Topic Watch Topic
  • New Topic

Must be caught or declared? Exceptions  RSS feed

 
Shananne DuFrame
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Eric Daly
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Then the only catch you consider is a NumberFormatException, though this is never thrown.

Actually it is thrown (from Integer.parseInt()). But since it is an unchecked exception you don't need to handle it.
 
Shananne DuFrame
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bunches. Got it!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!