why do some methods throw exceptions and how the calling method handles those exceptions?
Consider creating a network connection. Several things can happen without your control. You can lost internet connection, a transmission error can happen or the other side might close the port you are communicating.
To handle these types of errors appropriately and in an application specific way, exceptions exist in Java.
For example, for your network application, if some exception occurs, based on that exception, you can decide on application specific actions for that error. You might try to connect to another server (a backup server) as an example or you might show the user that his internet connection is lost and ask him to click retry button when he solved his problem with the internet connection.
So consider exceptions as the flexibility you gave to higher level applications for your API. With exceptions, you are giving application developers who use your API a choice! They can show a message to the user or just exit the application..
> How do i know my method can throw exception and i should include throws
> statement.
If you believe that the higher level applciation developer can handle that exception in different ways and should handle that exception, you will throw it. But if you think that there is no value to have such an exception, then just handle it in your own method.
> Also please give me the real world example of throwing exception.
Assume that you are developing a messenger library. You have a method to send a message to a user which has a method signature like:
void sendMessage(String username, String message)
When you call this method with sendMessage("John", "Hi"), it tries to send a message to the user John. But think about it a little bit. What kind of errors can happen while just trying to do such a simple call:
- User John might not be online: UserNotFoundException
- A network error can happen while transmitting the message: NetworkErrorException
- John might block your username: MessageBlockedException
For different methods there can be different errors. But the idea is to handle all these errors inside a simple try-catch block.
I hope it is clear now.