简体   繁体   English

如何创建可以抛出任何异常的通用函数?

[英]How to create general function which can throw any exception?

I have two classes(structure example): 我有两个类(结构示例):

public class A {
    protected void doCheck(stuff) throw CommonException, A1Exception{
        if(stuff==1){
            throw new A1Exception(stuff);
        }
        throw new CommonException(stuff);
    }
    public void invokeAstuff(stuff) throw CommonException, A1Exception{
        doCheck(stuff);
    }
}
public class B {
    protected void doCheck(stuff) throw CommonException, B1Exception{
        if(stuff==1){
            throw new B1Exception(stuff);
        }
        throw new CommonException(stuff);
    }
    public void invokeBstuff(stuff, otherStuff) throw CommonException, B1Exception{
        doCheck(stuff);
    }
}

"doCheck" methods have same logic for handling stuff, but have 1 different exception which can be thrown by each class: A1Exception for A class and B1Exception for B class “ doCheck”方法具有相同的逻辑来处理内容,但是每个类可以抛出1个不同的异常:A类为A1Exception,B类为B1Exception

My question is: How I can write basic class which will implement "doCheck" with common logic + take class of exception that should be thrown in some conditions? 我的问题是:如何编写将使用通用逻辑实现“ doCheck”的基本类+接受应在某些情况下抛出的异常类? A and B just should extend this class. A和B仅应扩展此类。

You could make a generic abstract class which declares the exception as a generic type, and then make a supplier method which you must override in the subclasses. 您可以创建一个将异常声明为通用类型的通用抽象类,然后创建一个必须在子类中重写的供应商方法。

public abstract class Checkable<X extends Exception> {

    protected abstract X getException(int stuff);

    protected void doCheck(int stuff) throws CommonException, X {
        if (stuff == 1) {
            throw this.getException(stuff);
        }
        throw new CommonException(stuff);
    }

}

A subclass would look like: 子类如下所示:

public class A extends Checkable<A1Exception> {

    @Override
    protected A1Exception getException(int stuff) {
        return new A1Exception(stuff);
    }

    public void invokeStuff(int stuff) {
        doCheck(stuff);
    }

}

Ideone Demo Ideone演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM