私はいくつかのワークフローに取り組んでおり、その中で多くの例外を発生させることができます。考えられるすべての例外を Enum (Exception1、Exception2 ...) に保持して使用できると聞きました。Java で列挙型を使用してそれを行うにはどうすればよいでしょうか?
3 に答える
            1        
        
		
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();
于 2012-12-19T18:18:24.047   に答える
    
    
            1        
        
		
例外のクラスを追加できます
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 
    } 
}
于 2012-12-19T18:14:04.457   に答える
    
    
            0        
        
		
例外を ArrayList に格納しないのはなぜですか? または、インデックスに名前を付けたい場合は、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;
    }
}
明らかに、またはのいずれArrayListかを使用するようにコードを変更する必要がありますHashMapが、これは列挙型を使用するよりも優れたソリューションになると思います。
于 2012-12-19T18:36:33.933   に答える