You should probably check this link to understand when should you handle the exceptions (try-catch) and when you should declare them (with throws clause): http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
Now, to answer your questions --
But isnt there a need to catch it in try/catch block?
Not always. It depends on the type of Exception. Java has two types of Exceptions: Checked
and Unchecked
. And Error
is a runtime situation from which recovery is not possible Read more about it at here http://docs.oracle.com/javase/tutorial/essential/exceptions/
For code that may throw checked exceptions, you MUST
provide one of below:
- try-catch block
- throws clause in method declaration
For code that may throw unchecked exceptions, you are not forced by the compiler to handle them or declare them. Though, you can do one of it, if you want.
How will i catch exceptions in this case?
In your case, both NotConnectedException
and UnauthorizedException
are unchecked exceptions. So you can (but not forced by the compiler) write try-catch block in your method code or you can declare them in throws clause. When you declare them in throws clause the callers of the method knows that these exceptions MAY
be thrown from it and plan to write their own try-catch for exception handling on their end.
When i try to call this function, then its mandatory to write try/catch block or write a throws clause in the calling function.
As I mentioned, both exceptions are unchecked (inherited from RuntimeException), so you are not required to do either. But you can do one of them.
Again, how will i catch these exceptions if i dont write a try/catch block?
you don't. The caller of the method will have to plan for exception handling with their own try-catch.
Catch or Specify
requirement: docs.oracle.com/javase/tutorial/essential/exceptions/…