Java P
Java P

Reputation: 2291

Keeping possible exceptions in Enum

I am working on some workflow and it is possible to raise many exceptions in that. I heard that we can keep all those possible exceptions in an Enum (Exception1, Exception2 ...) and use it. How can we do that using Enums in Java?

Upvotes: 1

Views: 768

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533660

You can add the classes of exceptions with

enum EnumWithExceptions {
    ENUM1(Exception1.class, Exception2.class),
    ENUM2(Exception3.class);

    private final Class<? extends Exception>[] exceptions;

    private EnumWithExceptions(Class<? extends Exception>... exceptions) {
        this.exceptions = exceptions;
    }

    public boolean matches(Exception e) {
        for(Class<? extends Exception> e2: exceptions)
            if (e2.isInstance(e)) return true;
        return false;
    }
} 

} catch(Exception e){ 
    if (ENUM1.matches(e)){ 
        //do something 
    } else if(ENUM2.matches(e)) {
        //do something 
    } else {
         //do something 
    } 
}

Upvotes: 1

user1914539
user1914539

Reputation:

Why not store the exceptions in an ArrayList? Or if you want to name the index, you could use a HashMap.

import java.util.ArrayList;
import java.util.HashMap;

public final class ExceptionStorage {
    private static int exceptionCount = 0;

    private static HashMap<String, Exception> indexedExceptions = new HashMap<>();
    private static ArrayList<Exception> exceptions = new ArrayList();

    public static void addException(Exception e) {
        exceptions.add(e);
    }

    public static void putException(Exception e) {
        indexedExceptions.put("Exception" + (++exceptionCount), e);
    }

    public static ArrayList<Exception> getUnindexedExceptions() {
        return this.exceptions;
    }

    public static HashMap<String, Exception> getIndexedExceptions() {
        return this.indexedExceptions;
    }
}

Obviously you would have to modify the code to use either ArrayList or HashMap, but I think this would be a better solution than using Enums.

Upvotes: 0

bmargulies
bmargulies

Reputation: 100123

enum Fred {
  SAM(AnException.class),
  I(AnotherException.class),
  AM(YetAnotherException.class)
  ;
   private Throwable t;
  Fred(Throwable throwable) {
       this.t = throwable;
  }
  public Throwable getThrowable() {
    return t;
  }

}

...

   throw Fred.SAM.getThrowable();

Upvotes: 1

Related Questions