Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't java unchecked exceptions be handled using try/catch block?

Tags:

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?

like image 266
Aravindh an Avatar asked Nov 12 '11 12:11

Aravindh an


People also ask

Can we use try catch block for checked exception?

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 unchecked exceptions be thrown?

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.

How do you fix unchecked exceptions in Java?

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.

What happens if a program does not handle an unchecked exception?

If the program does not handle an unchecked exception: B. the program is halted and the default exception handler handles the exception.


1 Answers

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).
like image 170
Michael Borgwardt Avatar answered Sep 20 '22 12:09

Michael Borgwardt