This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

throws clause

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the following code on page 352 K&B book


i intended to examine the usage of "throws ArithmeticException" in this tiny program, but with or without, it gives the same runtime exception, until i declare try block as shown above, the program runs fine.

May I ask how do we effectively implement throws clause?
 
P Ventura
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A division by zero between int, throws always an AritmethicExc.

ArExc is a RuntimeException, so you are free to omit declaration (throws near the method).
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ArithmeticException is a subclass of RuntimeException, so it's an unchecked exception. This means that it doesn't matter whether or not you explicitly declare it in your method's throws clause. The compiler will not require the calling code to handle the exception if you declare it, nor will it stop your code from throwing the exception if you don't declare it.

However, this isn't the case with checked exceptions. Normally you create your own exception class and then have your methods throw it to indicate an error condition. Here's a fairly typical example of how a real program might look like:
However, the above program will not compile. Since NoSuchWidgetException is a checked exception, the getWidget() method will not compile unless you declare that it throws the exception. And once you add a throws clause with a checked exception, the compiler will insist that you either put every invocation within an appropriate try...catch statement, or change the calling method to declare it too throws the exception. For instance:
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic