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
?
Yes, we can catch compile time exception (checked) and in the catch block we can wrap it with in a run time exception (unchecked) and re-throw it. But since we are re-throwing using checked exception we need to either wrap it inside an implicit try-catch pair or, skip handling it using the throws clause.
Can throw checked and unchecked exceptions. We can declare both types of exceptions using throws clause i.e. checked and unchecked exceptions. But the method calling the given method must handle only checked exceptions. Handling of unchecked exceptions is optional.
Handling ArrayIndexoutOfBoundException: Try-catch Block we can handle this exception try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations. The program will not terminate.
If the program does not handle an unchecked exception: B. the program is halted and the default exception handler handles the exception.
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 declared throws NullPointerException
because that is pretty much a given).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