Search code examples
javaexceptionarraylistcollectionsthrowable

How catch exceptions and store in a ArrayList


I am trying to catch exceptions generated while executing some methods in a list. I have created a different POJO class extending throwable class.

public class ErrorDetails extends  Throwable implements Serializable {


    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    private Exception errorDescription;


    public Exception getErrorDescription() {
        return errorDescription;
    }


    public void setErrorDescription(Exception errorDescription) {
        this.errorDescription = errorDescription;
    }

But still I cannot capture the exception in this manner.

private List<ErrorDetails> hello=new ArrayList<ErrorDetails>();
 catch (Exception e) {
            hello.add(e);

Solution

  • ErrorDetails is one specific type of Throwable. If you declare a list of ErrorDetails you can't add exceptions or errors in it. Change your code to use a list of Exception instead:

    List<Exception> hello = new ...
    

    I don't see a point to have your ErrorDetails class but in case you want to keep it, remove "extends Throwable" or replace it with something else. Throwable is meant to be a parent class only for Exception and Error.