Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"throw this" results in strange line in backtrace

Tags:

java

OK, this is one of the worst examples of programming ever, but I tried it while looking into someone else's question and found the results to be a bit bizarre. Any explanation?

public class Test {

    static class Bizarre extends RuntimeException {

        public void throwMe() {
            throw this;                   // line 6
        }

    }

    public static void main(String[] args) {
        Bizarre biz = new Bizarre();             // line 12
        System.out.println("Output line 1");     // line 13
        biz.throwMe();                           // line 14
        System.out.println("Output line 2");     // line 15
    }
}

Resulting output:

Output line 1
Exception in thread "main" Test$Bizarre
        at Test.main(Test.java:12)

Why line 12?

like image 876
ajb Avatar asked Jan 10 '23 09:01

ajb


1 Answers

An Exception's (Throwable really) stack trace is created at initialization. Your exception, a Bizarre instance, is created at line 12.

like image 178
Sotirios Delimanolis Avatar answered Jan 19 '23 13:01

Sotirios Delimanolis