Most of the java developers reads checked and unchecked exception difference, while reading difference below question may came in his/her mind.
Question-
In a tutorial I found that Unchecked Exception can't be handled by your code i.e. we can't use
try/catch
block and the examples are exceptions like ArrayIndexOutOfBoundsException, NullPointerException.
But these exceptions can be handled using try/catch block. I think i am not clear about the concept !!
Also i think throw keyword can be used only with
try/catch
block.can throw Keyword be used with UncheckedException
?Answer -
The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using
throws
, whereas with unchecked ones this is optional.Unchecked Exception can't be handled by your code i.e. we can't use try/catch block
Sure we can - but we don't have to.
Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with Unchecked Exception?
Note that there are two keywords:
throw
explicitly throws an exception object you created.throw new NullPointerException();
works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.throws
declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declaredthrows NullPointerException
because that is pretty much a given).
No comments:
Post a Comment