permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes throws clause Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "throws clause" Watch "throws clause" New topic

throws clause

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
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

Joined: Jan 24, 2007
Posts: 42
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).

Objective: SCJP 1.5<br /><a href="" target="_blank" rel="nofollow">API</a><br /> <blockquote><font size="1" face="Verdana, Arial">code:</font><hr><pre><font size="2"><br />Double n1 = Double.NaN; Double n2 = Double.NaN;<br /> n1.equals(n2) // true even though Double.NaN != Double.NaN<br />-0.0 == +0.0; // true<br />Double n1 = -0.0;Double n2 = +0.0;<br />n1.equals(n2) // false even though -0.0 == +0.0<br /></font></pre><hr></blockquote>
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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:

SCJP 5.0
adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
I agree. Here's the link:
subject: throws clause
jQuery in Action, 3rd edition