Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?

try {

  // Do something

} catch(IOException e) {

  throw new ApplicationException("Problem connecting to server");

} catch(Exception e) {

  // Will the ApplicationException be caught here?

}

I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.

1 Answer

0 votes
by (46k points)

If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:

public void doStuff() throws MyException {

    try {

        //Stuff

    } catch(StuffException e) {

        throw new MyException();

    }

}

And now your compiler will not yell at you :)

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...