This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
So, I've used the throws clause several times, but only because of the compiler's warnings. I know that an exception must either be caught(try,catch) or declared(throws), but i'm not sure i fully understand this strategy.
Let me do a short recap and please tell me if i'm wrong:
1. Throws clause tells the compiler and the client that the a method could throw an exception.
2. Is used in a method which calls another method that throws an uncaught exception.
The strategy here is to pass the Exception along the method call stack until some code knows how to recover of handle the Exception. For example, a JDBC library may cause a SQLException to occur. That library can't know what you need to do to fix the exception, so it throws it. Your immediate method which calls the JDBC library may not know what to do either, maybe it is too far down the chain to be able to do anything to fix the problem, so your immediate calling function throws the exception as well. So you keep passing the function up the method calls until finally a method can do something with it. Perhaps it can check the SQLException and determine that it needs to clean up an old connection, reset some variables, open a new connection, and re-try the entire operation from scratch. Maybe it can figure out the exception comes from bad data, and so can log it, inform the GUI, and skip the operation. Maybe the exception signals the certain death of all future operations, and so it logs it, cleans up resources, and exits the application gracefully.
So the point is, the immediate code which generates the exception may not know what to do, so you need to keep throwing it until you get to code that can respond appropriately and safely. Once you are at a level which can respond you need to catch the Exception and take appropriate action.
if the code may gose wrong what you don't know the reason ,you should try catch around it ,and if you add a declare of throws before a method ,it's means that the method may throw an exception and you should try catch is or throw the exception to the father method.