Explore BrainMass

Explore BrainMass

    Java: Throwing Exceptions

    Not what you're looking for? Search our solutions OR ask your own Custom question.

    This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

    Please help in understanding how Java can someone help answer these two questions regarding about throwing exceptions (see attachment).

    © BrainMass Inc. brainmass.com March 4, 2021, 9:24 pm ad1c9bdddf
    https://brainmass.com/computer-science/java/java-throwing-exceptions-241032

    Attachments

    Solution Preview

    Question:

    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 ...

    Solution Summary

    The solution answers questions regarding throwing exceptions.

    $2.49

    ADVERTISEMENT