3.12. Throwing and Handling Exceptions

Exceptions are thrown from programs using the throw keyword. Its compilation is simple:

void cantBeZero(int i) throws TestExc {    if (i == 0) {        throw new TestExc();    }}


Method void cantBeZero(int)0   iload_1             // Push argument 1 (i)1   ifne 12             // If i==0, allocate instance and throw4   new #1              // Create instance of TestExc7   dup                 // One reference goes to its constructor8   invokespecial #7    // Method TestExc.<init>()V11  athrow              // Second reference is thrown12  return              // Never get here if we threw TestExc

Compilation of try-catch constructs is straightforward. For example:

void catchOne() {    try {        tryItOut(); ...

Get The Java® Virtual Machine Specification, Java SE 7 Edition, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.