Why would java require this what are some benefits of


You will have noticed in the reading about throwing exceptions, that some exceptions (such as java.io.IOException) must be caught by your code whenever you do something that may throw them, otherwise the Java compiler complains. Any method you write that can throw such an exception must be declared as throws ExceptionName. This is the way it works for most exceptions: you must declare that you can throw them, and you must handle them if they can be thrown.

Question 1:

Why would Java require this? What are some benefits of requiring that exceptions be either explicitly handled or rethrown?

Other exceptions (such as java.lang.ArrayIndexOutOfBoundsException and java.lang.NullPointerException) can be used or ignored freely: any method can throw them anytime, and you don't have to catch them (although you can if you want to).

The difference is that ArrayIndexOutOfBoundsException and NullPointerException are both subclasses of java.lang.RuntimeException. Java makes a special case for any exception that is derived from RuntimeException: it can be thrown at any time, you don't have to declare that you will throw it, and you don't have to catch it if it is thrown.

Question 2:

Why is there this special case for some exceptions? What is different about something like ArrayIndexOutOfBoundsException that makes it beneficial to not have to enclose every statement that could produce it with a try/catch?

Solution Preview :

Prepared by a verified Expert
JAVA Programming: Why would java require this what are some benefits of
Reference No:- TGS01250355

Now Priced at $20 (50% Discount)

Recommended (93%)

Rated (4.5/5)