Exceptions - Throw and catch right away

前端 未结 2 1429
终归单人心
终归单人心 2021-01-22 10:16

Does it make sense to throw an exception and directly catch it just to print error?

if(...){

} else {
   try{
      throw new Exception();
   } catch (Exception         


        
相关标签:
2条回答
  • 2021-01-22 11:09

    There's no need to throw-and-catch, you can simply call:

    new Exception().printStackTrace();
    

    or even easier:

    Thread.dumpStack();
    

    You can also get the stack trace from the current thread as an array:

    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    

    If you want to do something more detailed like inspect the stack at runtime (e.g. to get the calling method's name).

    0 讨论(0)
  • 2021-01-22 11:12

    I think it might be useful only if you explicitly want to send the Exception to a log file with a LOGGER (into the catch block), or register it in an especific way.

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