0

This program is for exception handling, but the problem point is at UserException????

import org.omg.CORBA.UserException;

    public class Ch9_3_3 {

    class UserException extends Exception {
        int data;
        public UserException(int d) { data = d; }
        public String getMessage() {
            return ("Error! You negotiate too much for auction price: " + data);
        }
    }

    public static void main(String[] args) {
        try {
            for ( int i = 0; i < 5; i++) {
                if (i==3) throw new UserException(3);
                System.out.println("No. of auction: " + i);
            }
        }
        catch ( UserException ex) {
            System.out.println("Exception note: " + ex.getMessage());
            System.out.println("Exception reason: ");
            ex.printStackTrace();
            return;
        }
        finally { System.out.println("Error handling completed."); }
        System.out.println("End of program!");
    }

}

With error message: Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type Ch9_3_3 is accessible. Must qualify the allocation with an enclosing instance of type Ch9_3_3 (e.g. x.new A() where x is an instance of Ch9_3_3). at Ch9_3_3.main(Ch9_3_3.java:16)

Note: Line 16 is try {

Snowman
  • 59
  • 1
  • 10

1 Answers1

0

There is a compilation error in your code below

 if (i==3) throw new UserException(3);

You can't create an instance of an inner class like this. Instead you can either

make the inner class static. since you calling it from the main class.

public static class UserException extends Exception

or can make the object as below

if (i==3) throw new Ch9_3_3().new UserException(3);
vineeth sivan
  • 510
  • 3
  • 18
  • The program can be run now, but it's strange, result is as below. _Exception reason: Error handling completed. Ch9_3_3$UserException: Error! You negotiate too much for auction price: 3 at Ch9_3_3.main(Ch9_3_3.java:16)_ – Snowman Feb 22 '16 at 05:14
  • That's what you program for. Whats strange in it? – vineeth sivan Feb 22 '16 at 05:17