-3

Here is my code:

public static void main(String[] args) {
    System.out.print("a");
    try {
        System.out.print("b");
        throw new IllegalArgumentException();
    } catch (IllegalArgumentException e) {
        System.out.print("c");
        throw new RuntimeException("1");
    } catch (RuntimeException e) {
        System.out.print("d");
        throw new RuntimeException("2");
    } finally {
        System.out.print("e");
        throw new RuntimeException("3");
    }
}

I can not understand why the output is abce and RuntimeException("3")

Oleg
  • 6,124
  • 2
  • 23
  • 40
karim
  • 5
  • Hint: tried reading some book or tutorial about how exceptions and try/catch work? – GhostCat Jul 30 '17 at 18:37
  • You should give a tour to Exception tutorial which is the one of the specification of java. https://docs.oracle.com/javase/tutorial/essential/exceptions/ – atiqkhaled Jul 30 '17 at 18:53
  • First time I downvote a question. Unlike others I'm all for helping people with simple problems but this is too much. Why couldn't you google "java exception catch finally" and look throw the first 3 or 4 links? – Oleg Jul 30 '17 at 19:55

3 Answers3

3

That becomes clear when you indent your code as it should be:

try {
  System.out.print("b");
  throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
  System.out.print("c");
  throw new RuntimeException("1");
} catch (RuntimeException e) {
  System.out.print("d");
  throw new RuntimeException("2");
} finally {
  System.out.print("e");
  throw new RuntimeException("3");
}

The point is: there is only one try block. And the first catch block is taken. That one throws - and this exception 1 would be the one you notice in your stacktrace.

But thing is: the finally block is throwing "on top" of exception 1. Therefore you see exception 3.

In other words: there is a misconception on your end. You probably assume that exception 1 should be caught by the second catch block. And that is wrong. The second catch block only covers the first try block. Meaning: an exception from a catch block does not result in another catch block being taken. The first catch block "fires", and the finally block "fires" - leading to the observed results.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

While you can have many catch() blocks, a maximum of 1 catch() will be executed when an exception is thrown. After that it will execute finally block, hence you have the output abce and the RuntimeException from finally block.

Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
0

It is because, after IllegalArgumentException thrown in try block, it is caught in corresponding catch (IllegalArgumentException e) { } block. As finally block gets executed regardless of exception, e get printed.

To your question, Since the exception was already caught in catch block it will throw the corresponding exception accordingly and it will get propagated to the caller of that method.