Can somebody explain me what is the use of throws Exception in java? Its just used to indicate that the method will throw the exception specified? The calling method need to catch the exception specified?
So instead of throws we can use a try-catch block to catch the exception?
How it differs from throw? Thanks
Java uses explicit exception handling - except of RuntimeException
s, every exception thrown [by the method itself, or a method it invokes declares it throws
it]- must be handle or declared in the method signature.
It allows safety, since when you invoke a method you know exactly which errors might occur, which you can then either handle locally with try/catch
blocks, or declare as part of your method signature.
Although @amit already gave very good answer I just want to add something.
So instead of throws we can use a try-catch block to catch the exception?
I think that this part of your question was not answered. Actually you are asking whether you should define methods that are "transparent" for exceptions or catch exceptions thrown within the method.
The answer is that it depends on your application. Generally there are 2 cases when you want to catch exception into the method.
You do not want to expose the exceptions thrown on specific layer of your application to higher level layers. In this case you will probably wrap your code with try block and wrap thrown exception with other level exception:
try { // some code } catch(IOException e) { throw new ApplicationLevelException(e); }
In most other cases you will probably want to be transparent for exceptions and catch all exception in one single point that knows what to do with them. For example shows customer facing error message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With