Close

Java - Exception Generic Classes and Type Parameters

[Updated: May 15, 2018, Created: May 15, 2018]

Java does not allow generic exception classes (JLS ref). That's because of the type erasure. Generic types are not reifiable in catch clauses.

Following will not compile:

package com.logicbig.example;

public class ExceptionGenericClass {

    public static class MyException<T> extends Exception {

        private final T t;

        public MyException(T t) {
            super();
            this.t = t;
        }

        public T getT() {
            return t;
        }
    }

    public static void process() throws MyException<String> {
        throw new MyException<>("test exception");

    }

    public static void main(String[] args) {
        try {
            process();
        } catch (MyException<String> e) {
            System.out.println(e.getT());
            e.printStackTrace();
        }
    }
}

Compile time errors:

com\logicbig\example\ExceptionGenericClass.java:5: error: a generic class may not extend java.lang.Throwable
    public static class MyException<T> extends Exception {
                                               ^
1 error

However, generic type parameter can be used in throws clause

package com.logicbig.example;

import java.io.IOException;
import java.util.zip.ZipException;

public class ExceptionGenericTypes {

    public static abstract class Task<E extends IOException> {
        public abstract void process() throws E;
    }

    public static class SubTask extends Task<ZipException> {

        @Override
        public void process() throws ZipException {
            throw new ZipException();
        }
    }

    public static void main(String[] args) {
        try {
            Task<ZipException> a = new SubTask();
            a.process();
        } catch (ZipException e) {
            e.printStackTrace();
        }
    }
}

On running above class:

java.util.zip.ZipException
	at com.logicbig.example.ExceptionGenericTypes$SubTask.process(ExceptionGenericTypes.java:16)
	at com.logicbig.example.ExceptionGenericTypes.main(ExceptionGenericTypes.java:23)

See Also