permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help Sought in the difference between throws and throw? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Help Sought in the difference between throws and throw?" Watch "Help Sought in the difference between throws and throw?" New topic

Help Sought in the difference between throws and throw?

gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924

If a method or constructor declares to throw an exception using keyword "throws" is it mandatory that somewhere it should really throw that exception using "throw" keyword.?? I may be wrong but when i opened source file for FileWriter class , the constructor of FileWriter declares to throw IOException(throws IOException) but nowhere in the class there was something like . I think i'm confused between this throw and throws jargon.

My second question is related to code listing shown below:
Code Listing 1

In the above code listing MyException(which is a checked exception) is being thrown manually using throw keyword. I know that the code wont compile because i have to honor java's catch or specify requirement for checked exceptions. so to make this code compile i have to do the following changes as shown below :

Code Listing 2

Referring to codel listing 2 , can i do this(Refer code listing 3)

Here i omitted throw clause and declared that doStuff() throws MyException(Same way the FileWriter constructor declares to throw IOException but doesn not use any throw keyword. ?? Please help me in this regard
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Yes, you're allowed to declare a method as throwing a checked exception it doesn't actually throw. Just to take an extreme example - an interface is allowed to declare a method as potentially throwing a checked exception (see, for example,, which is implemented by Writer and OutputStream).

The reason for this is that a subclass might override the method and throw the exception. And one of the restrictions when overriding a method is that you aren't allowed to introduce new checked exceptions into the throws list (the compiler won't allow it). So using the same example, the only reason Writer.close() is allowed to throw an IOException is because the interface declares it.

Looking at the particular case you refer to. The FileWriter constructor doesn't say throw new IOException anywhere. But it does create a new FileOutputStream, and that also has a constructor that is declared to throw IOException. So the constructor of FileWriter has to as well. If you follow the chain back, you'll eventually find native methods in FileOutputStream that can throw IOException.
I agree. Here's the link:
subject: Help Sought in the difference between throws and throw?
It's not a secret anymore!