12

I am wondering why the Exception in the following bytecode (used to throw an Exception) is duplicated.

NEW java/lang/IllegalArgumentException
DUP
INVOKESPECIAL java/lang/IllegalArgumentException <init> ()V
ATHROW
1
  • I just add my two cents. NEW just allocates object memeory without calling any constructor, INVOKESPECIAL will call a construction but that call will pop from a stack this pointer and push nothing (constructors return void). By convention compilers targeting JVM will generate above NEW/DUP/INVOKESPECIAL sequence to create a new object. This is a pattern that is recognized by JVM and may be specially optimized... Commented Feb 20, 2018 at 15:03

2 Answers 2

21

I'll analyze this line by line where [] = new stack after that op is used:

  1. NEW puts a new IllegalArgumentException onto the stack [SomeIllegalArgumentException]
  2. DUP duplicates it [SomeIllegalArgumentException, SomeIllegalArgumentException]
  3. INVOKESPECIAL pops off the top one and initializes it by calling it's <init> method [SomeIllegalArgumentException] (The init method will not return the object to put back onto the stack, so the object must first be duplicated so as to keep it on the stack)
  4. ATHROW Throws the other (a duplicate off the one we initialized) []
Sign up to request clarification or add additional context in comments.

1 Comment

This is easier to understand if you think less of it popping and pushing objects themselves on the stack and instead talk about references.
11

In byte code, an object is first created by class, and then a constructor is called on that object. The signature of a constructor ends with V for void as it does return anything. This means a copy of the original reference to the object must be kept on the stack (or in a variable) so it can be thrown after the constructor is called.

BTW The internal name for a constructor is <init> and the internal name for a static initialiser code is <clinit>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.