例外 - 立即投掷并抓住 [英] Exceptions - Throw and catch right away

查看:143
本文介绍了例外 - 立即投掷并抓住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if(...)是否有意义的引发异常? {

} else {
try {
throw new Exception();
} catch(Exception e){
e.printStackTrace();
}
}


解决方案

没有必要抛出,你可以直接调用:

  new Exception()。printStackTrace(); 

甚至更容易:

  Thread.dumpStack(); 

您还可以从当前线程获取堆栈跟踪作为数组:

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

如果你想做更详细的事情,例如在运行时检查堆栈(例如,获取调用方法名称)。


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

if(...){

} else {
   try{
      throw new Exception();
   } catch (Exception e){
      e.printStackTrace();
   }
}

解决方案

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).

这篇关于例外 - 立即投掷并抓住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆