Exception handling try catch inside catch

前端 未结 3 1847
别跟我提以往
别跟我提以往 2020-12-13 17:59

I recently came across code written by a fellow programmer in which he had a try-catch statement inside a catch!

Please forgive my inability to paste the actual code

相关标签:
3条回答
  • 2020-12-13 18:13

    Without knowing what the code does it's impossible to say. But it's not unusual to do this.

    e.g. if you have to clear up resources whilst handling exceptions, that clear-up code itself may have the capability to throw exceptions.

    0 讨论(0)
  • 2020-12-13 18:20

    Here is a case :

    try{
        //Dangerous Operation
    } catch (AnyException ae) {
        try {
            //Do rollback which can fail
        } catch (RollbackFailedException rfe) {
            //Log that
        }
    } finally {
        try {
            //close connection but it may fail too
        } catch (IOException ioe) {
            //Log that
        }
    }
    

    It's about the same thing as @x0n said. You might need to handle exception while try to close resources or while you're trying to resolve a situation brought by another exception.

    0 讨论(0)
  • 2020-12-13 18:21

    Why is that bad? It's no different conceptually than:

    void TrySomething() {
       try {
    
    
       } catch (ArgumentException) {
            HandleTrySomethingFailure();
       }
    }
    
    void HandleTrySomethingFailure() {
        try {
    
        } catch (IndexOutOfRangeException) {
    
        }
    }
    

    Before you go over there and give him a piece of your brain (try the parietal lobe, it's particularly offensive) , what exactly are you going to say to him? How will you answer the proverbial "why?"

    What's even more ironic is that when the jitter inlines this code, it will look exactly like your example.

    -Oisin

    0 讨论(0)
提交回复
热议问题