java - What does "Throws" do and how is it helpful? -
this question has answer here:
- the throws keyword exceptions in java 4 answers
i new java , have came across tutorial uses the"throws" keyword in method. have done little research still not understand it.
from have seen far, telling compiler exception may thrown in particular method. why need tell compiler this? have made many programs using merely try-catch statement in methods , has worked fine - surely these try-catch statements manage exceptions, right?
you can manage exception within method using try
, catch
say. in case, not need use throws
. example:
public void mymethod() { try { /* code might throw exception */ } catch (spaceinvadersexception exception) { /* complicated error handling code */ } }
but suppose had thousand methods, of might throw spaceinvadersexception
. end having write complicated error handling code thousand times. of course, create errorhandler
class dealwithspaceinvadersexception()
method call them, you'd still stuck thousand try
-catch
blocks.
instead, tell compiler each of these thousand methods throw spaceinvadersexception
. method calls 1 of these methods needs deal error itself, either using try
-catch
, or telling compiler it might throw spaceinvadersexception
. done using throws
keyword, this:
public void mymethod() throws spaceinvadersexception { /* code might throw exception */ } public void callingmethod() { try { mymethod(); } catch (spaceinvadersexception exception) { /* complicated error handling code */ } }
in case, need inform compiler mymethod
throw spaceinvadersexception
. means can't call method without dealing exception in way (try
-catch
or using throws
keyword on calling method). if throws
weren't there, call method without doing exception handling, , exception wasn't dealt anywhere in program (which bad).
since better avoid code duplication, better palm off error handling try
-catch
in higher level function deal separately in of low level methods. why mechanism exists.
Comments
Post a Comment