dunder69
dunder69

Reputation: 21

Java: Getting ExceptionInInitializerError for Enums

EDIT: Solved but I don't understand why

In PokemonEnum I had this line

private PokemonEnum[ ] pokemon = PokemonEnum.values(); 

I changed it to:

private static PokemonEnum[ ] pokemon = PokemonEnum.values(); 

and now it works. I never even used that array yet so I don't know why I was getting errors or why static fixed it.


I haven't really worked with Enums so I don't really know why I get an ExceptionInInitializerError when I run main (on line 28 when I try to create a new Pokemon). Anyone care to explain please? Thanks.

import java.awt.image.BufferedImage;
import java.util.ArrayList;


public class Pokemon {

    private PokemonEnum name;
    private int dexNumber;
    private BufferedImage sprite;
    private TypeEnum[] types = new TypeEnum[1];
    private ArrayList<AbilityEnum> abilities;
    private ArrayList<MoveEnum> moves;
    private short hp;
    private short attack;
    private short defense;
    private short special_attack;
    private short special_defense;
    private short speed;

    public Pokemon(PokemonEnum name)
    {
        this.name = name;
        this.dexNumber = name.getDexNum();
    }

    public static void main(String[] args)
    {
        Pokemon pikachu = new Pokemon(PokemonEnum.Pikachu);
        System.out.println(pikachu.dexNumber);
    }
}



   public enum PokemonEnum {
    Pikachu;

    public int getDexNum()
    {
        return ordinal()+1;
    }

    private PokemonEnum[ ] pokemon = PokemonEnum.values(); 
}


Stack Trace:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at Pokemon.main(Pokemon.java:28)
Caused by: java.lang.NullPointerException
    at PokemonEnum.values(PokemonEnum.java:1)
    at PokemonEnum.<init>(PokemonEnum.java:722)
    at PokemonEnum.<clinit>(PokemonEnum.java:2)
    ... 1 more

Upvotes: 2

Views: 4533

Answers (1)

merlin
merlin

Reputation: 564

What you are experiencing is 'like' a recursion.

This error occurs because the code PokemonEnum.values() is in the enum PokemonEnum and when this is compiling it reads values() and then using this internal function, the primitive data type enum references to itself. However due to the fact that the enum is still being compiled, the value of value() is null.

Note: Trying to use the value() inside of it's enum will result in an Error. Such that trying to use if(PokemonEnum.values()!=null) or even trying to catch the ExceptionInInitializerError will not work due to the values() being part of a primitive type(meaning the method being called is native).

The Solution would be to place private PokemonEnum[] pokemon = PokemonEnum.values(); outside and below the enum PokemonEnum.

I know this from personal experience as well as other sources on similar problems.

Similar Sources: here and here

Hope this helps.

Upvotes: 4

Related Questions