How to manage exceptions in this code?

时间:2016-04-04 18:09:03

标签: java exception exception-handling

I was wondering why I can't use throw in the nested catch below, I get an error. What is the way to handle exceptions well in this case?

try {
    /* some code which can throw DataAccessException */
    try {
        /* some code which can throw FileNotFoundException */
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }       
} catch (DataAccessException e) {
    e.printStackTrace();
    throw e;
}

Another example, I'm not sure if I handle exceptions well. I'm not sure about printing the stack trace, is it a good practice?

public class SomeCode {

    public static void main(String[] args) {
        A a = new A();
        a.method1();
    }
}

class A {

    B b = new B();

    public void method1() {

        log.info("I'm gonna call method 2");
        try{
            b.method2();
            log.info("success");
        }
        catch(Exception e) {
            log.info("failure");        
        }
    }
}

class B {

    C c = new C();

    public void method2() {
        log.info("I'm method 2 and I'm gonna call method 3");
        try{
            c.method3();
            log.info("success");
        }
        catch(Exception e) {
            throw e;        
        }
    }
}

class C {

    public void method3() {
        log.info("I'm method 3!");
        try{
            log.info("woo-hoo!");
            /*
                some code which can throw DataAccessException.
            */
        }
        catch(DataAccessException e) {
            e.printStackTrace();
            throw e;
        }
    }
}

Any advices on how to handle exceptions better will be very appreciated.

4 个答案:

答案 0 :(得分:1)

Catching exceptions totally depends on the usecase, now lets see what it means:

  1. If you just don't want the code to break, or the user to know that the code broke.

    try {
    
        // Some code 
    } catch( Exception e){
        // Log the exception or print trace, so that you can understand that later.
        return <Something> // Depends on the function
    }
    

Or it may be possible you want to handle each case in a different manner , for example lets say the function is to explain the user what happened:

    try {
        // Some code 
    } catch( FileNotFoundException e){
        return “File was not found, try other file”;
    } catch( Exception e){
        Log(“There was an error”);
        return “ Something didn’t go as expected ,              please try later”;
    }

Or you can use your own exception classes,

    try {
        // Some code
    } catch (Exception e){
        throw new PersonalProjectException();
    }

答案 1 :(得分:1)

Just my two cents. On your second example you don't need to use try/catch block on class B as you are just rethrowing the exception. I would re-write that as the following:

class B {

    C c = new C();

    public void method2() throws Exception {
        log.info("I'm method 2 and I'm gonna call method 3");
        c.method3();
        log.info("success");            
    }
}

Printing the stack trace can help the developer understand what is happening but on your example you are ignoring the exception after printing it.

Personally I try to avoid propagating the Exception. If the system can't handle it and recover I prefer to throw an unckecked Exception after catching a checked one and cleaning any resources.

If you have the opportunity take a look at chapter 7 on Clean Code book. It covers error handling and is very useful.

答案 2 :(得分:0)

Without better explanation as to the specific error you are receiving, it is hard to answer the first part of your question. However, as the code below demonstrates, there is nothing wrong with the nested exceptions:

public static class DataAccessException extends Exception
{
}



public static void daeMethod() throws DataAccessException
{
}



public static void fneMethod() throws FileNotFoundException
{
}


// this method compiles and executes fine, throwing a DataAccessException
// but catching an ignoring a FileNotFoundException
public static void compoundMethod() throws DataAccessException
{
    try {
        daeMethod();
        try {
            fneMethod();
        }
        catch (FileNotFoundException e) {
        }
    }
    catch (DataAccessException e) {
        throw e;
    }
}

Based upon a comment, adding an example of where I might not care about an exception. Assume I am attempting to parse a potential configuration setting.

double d = 2.5; //my default
String s = configuration.getCfg(SomeParameter);
try {
  d = Double.parseDouble(s);
}
catch (NumberFormatException whoCares) {
  //just ignore it; use the default
}

In this case, I will use the default unless a valid entry is present. I could inform the user that no setting was found, or a bad setting was found, or whatever. However, I may not care. The default works unless there is a specific, valid value in the file.

答案 3 :(得分:0)

The correct way to nest exceptions is as shown below:

try {
   /* some code which can throw some Exception*/
}catch (FileNotFoundException e) {
   e.printStackTrace();
}catch (DataAccessException e) {
   e.printStackTrace();
   throw e;
}catch(Exception e){
   e.printStackTrace();
   throw e;
}

if the code throws an exception depending on the type enters the appropriate catch.

regards!

相关问题