In a Java catch block, how do you know which method / line throws an exception?

In the try block, I want to perform two functions. If the first failed, do not follow the second. I also want to print which function failed.

See the following code.

try {
  a = func1();
  b = func2();  //won't execute if a failed
}
catch (Exception e) {
  //TODO: print a or b failed?
}

Does the language support this scenario naturally?

If not, is the following practice good? (I can't think of anything bad, but that concerns me, as I don't remember anyone using returnin catch.)

try {
  a = func1();
}
catch {
  //print: a failed
  return; //if a failed then skip the execution of b
}

try {
  b = func2();
}
catch {
  //print: b failed
}

EDIT: Summary of Comments:

  • throws another exception to the two methods.

    • In this case, the methods are written by others, and I do not control.
  • e.printStackTrace () will print the line number and function

    • I want to do more than just print. Moreover, if it fails, run the following code.
+4
5

String methodName = e.getStackTrace()[0].getMethodName());

. ( , Java), , , PrintStream, printStackTrace(printStream).

( ) . . 99% , .

+4

:

String failedFunc = "func1";
try {
    a = func1();
    failedFunc = "func2";
    b = func2();  //won't execute if func1() failed
} catch (Exception e) {
    System.out.println("Func '" + failedFunc + "' failed: " + e);
}

, , , , , , . , failedFunc .

+1

, . try/catch , .

+1

dev-null e.getStackTrace(). , func1 func2, , . , func1 func2.

try , .

+1

, e.printStackTrace(), Exception. , . , func1 func2 Exception s. - ,

class Func1Exception extends Exception {
    public Func1Exception(Exception e) {
        super(e);
    }
}

class Func2Exception extends Exception {
    public Func2Exception(Exception e) {
        super(e);
    }
}

,

private static Object func1Decorator() throws Func1Exception {
    try {
        return func1();
    } catch (Exception e) {
        throw new Func1Exception(e);
    }
}

private static Object func2Decorator() throws Func2Exception {
    try {
        return func2();
    } catch (Exception e) {
        throw new Func2Exception(e);
    }
}

Then you can process them however you want.

try {
    a = func1Decorator();
    b = func2Decorator(); // this still won't execute if a failed
} catch (Func1Exception e) {
    // a failed.
} catch (Func2Exception e) {
    // b failed.
}

If you want to func2start even in case of failure, you can use the block finally,

try {
    a = func1Decorator();
} catch (Func1Exception e) {
    // a failed.
} finally {
    try {
        b = func2Decorator(); // this will execute if a fails
    } catch (Func2Exception e) {
        // b failed.
    }
}
+1
source

Source: https://habr.com/ru/post/1624527/


All Articles