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
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, java.io.Closeable, 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.