Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of throws Exception

Tags:

java

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

like image 786
mee Avatar asked Apr 17 '12 08:04

mee


2 Answers

Java uses explicit exception handling - except of RuntimeExceptions, 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.

like image 80
amit Avatar answered Oct 04 '22 02:10

amit


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.

  1. you have something to do with the exception, so your flow depends on the fact that the exception was thrown. For example if you are reading from file and IO error happens you are trying to read from the file again.
  2. 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.

like image 24
AlexR Avatar answered Oct 04 '22 02:10

AlexR