Exception is swallowed by finally

前端 未结 7 1915
攒了一身酷
攒了一身酷 2020-12-08 23:54
static int retIntExc() throws Exception{
    int result = 1;
    try {
        result = 2;
        throw new IOException(\"Exception rised.\");
    } catch (ArrayInd         


        
7条回答
  •  猫巷女王i
    2020-12-09 00:30

    By putting return in finally method you override thrown exception and result is returned instead. Your code should be something like this:

    static int retIntExc() throws Exception{
            int result = 1;
            try {
                result = 2;
                throw new IOException("Exception rised.");
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println(e.getMessage());
                result = 3;
            } finally {
                // do something
            }
            // it gets here only when exception is not thrown
            return result;
        }
    

提交回复
热议问题