Home > Net >  Exception handling in nested methods with more than 2 levels deep
Exception handling in nested methods with more than 2 levels deep

Time:10-07

Let's say we have nested methods A, B and C like below:

public void A(){
    try{
        B();
    }
    catch(Exception e){
        log.error(e);
    }
}

public void B(){
    C();
}

public void C(){
    try{
        some_stuff();
    }
    catch(Exception e){
        log.error(e)
    }
}

Since I catch the exception at C() and handle it with only logging, and there isn't any catch in B(), do I catch the exception at A()?

Or should I throw the exception at C() and add a try catch at B() to be able to handle it in A()?

CodePudding user response:

When you do

public void C(){
    try{
        some_stuff();
    }
    catch(Exception e){
        log.error(e)
    }
}

This will handle the exception at this point. You will log it and disregard the exception. If you want to log and propagate it up, you need to re-throw it from the catch clause.

Since Exception is checked (as far as I remember) you need to change the method signature to indicate that you are throwing this from C.

At B you don't need to handle it, you can just change the method signature to indicate the method throws Exception.

Read more on Java checked vs unchecked exceptions for example here enter link description here

Finally if you want to propagate to A the code will look like this:

public void A(){
    try{
        B();
    }
    catch(Exception e){
        log.error(e);
    }
}

public void B() throws Exception{
    C();
}

public void C() throws Exception{
    try{
        some_stuff();
    }
    catch(Exception e){
        log.error(e)
        throw e;
    }
}

CodePudding user response:

You are handling the exception in the catch block, therefore it will not be further propagated to the caller. This is independent of whether you are logging it or doing anything else with it. If you want want to propagate it to the caller, you would need to re-throw it:

[...]
catch (Exception e) {
   // do something
   throw e;
}

How you handle exceptions depends on the design of your code.

  • Related