How to propagate an exception in java

后端 未结 4 1827
無奈伤痛
無奈伤痛 2020-12-19 00:30

I am a C programmer and just learning some java recently because I am developing one android application. Currently I am in a situation. Following is the one.



        
4条回答
  •  无人及你
    2020-12-19 01:24

    Just don't catch the exception in the first place, and change your method declaration so that it can propagate them:

    public void myMethod() throws ExceptionType1, ExceptionType2 {
        // Some code here which can throw exceptions
    }
    

    If you need to take some action and then propagate, you can rethrow it:

    public void myMethod() throws ExceptionType1, ExceptionType2 {
        try {
            // Some code here which can throw exceptions
        } catch (ExceptionType1 e) {
            log(e);
            throw e;
        }
    }
    

    Here ExceptionType2 isn't caught at all - it'll just propagate up automatically. ExceptionType1 is caught, logged, and then rethrown.

    It's not a good idea to have catch blocks which just rethrow an exception - unless there's some subtle reason (e.g. to prevent a more general catch block from handling it) you should normally just remove the catch block instead.

提交回复
热议问题