Exceptions - Throw and catch right away

前端 未结 2 1438
终归单人心
终归单人心 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).

提交回复
热议问题