Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions as well as catching exceptions?

I was wondering how Java takes the following scenario

public static void main(String[] args) throws IndexOutOfBoundsException, CoordinateException, MissionException, SQLException, ParserConfigurationException {
    try {
        doSomething();
    } catch (Exception e) {
        e.printStackTrace();
    } 
}

In the above code, I am declaring the main function to throw many different exceptions, but inside the function, I am catching the generic Exception. I am wondering how java takes this internally? I.e., say doSomething() throws an IndexOutOfBounds exception, will the e.printStackTrace() get called in the last catch (Exception e) {...} block?

I know if an exception not declared in the throws area of the function gets thrown, the try/catch will handle it, but what about exceptions mentioned in the declaration?

like image 721
E.S. Avatar asked Jan 13 '23 01:01

E.S.


2 Answers

In your case if ANY Exception is thrown or generated in doSomething() it will be caught in the try-catch block because of the Exception e you are catching.

Exception is the parent of all Exceptions. All Exceptions inherit from this class.

like image 170
MaVRoSCy Avatar answered Jan 22 '23 17:01

MaVRoSCy


The catch block has greater priority over the method level throw declarations. If something would pass by that catch block, it would be thrown by the method (but that's not the case since all your mentioned exceptions are indeed inheriting from the Exception).

If you need an exception to be handled by the catch block but forwarded further, you would have to rethrow it, e.g.

throw e;
like image 31
darijan Avatar answered Jan 22 '23 18:01

darijan