前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Java】 NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException、ArrayIndexOutOfBoundsE

【Java】 NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException、ArrayIndexOutOfBoundsE

作者头像
NaughtyCat
发布2020-10-09 16:28:47
8550
发布2020-10-09 16:28:47
举报
文章被收录于专栏:开心的平凡酱开心的平凡酱

今天工作中,临时Fix一个bug,一看日志“java.lang.ClassCastException: null” 相当懵逼,没有详细堆栈信息,这咋整。虽然根据上下文可以推测问题代码的大致位置,但不敢拍板啊。只好google找一下,在Stackoverflow上果然有解决办法

【解决方法】

  在java启动命令中添加“-XX:-OmitStackTraceInFastThrow”即可输出详细堆栈信息——亲测可用。

【问题原因】

JVM(HotSpot JVM)进行了优化。当第一次发生异常(通常为NullPointerException)时,将打印完整的堆栈跟踪,并且JVM会记住堆栈跟踪(或者可能只是代码的位置)。 当该异常经常发生时,将不再打印堆栈跟踪,这既可以实现更好的性能,【CoederBaby】又不会使相同的堆栈跟踪充满日志

【进一步分析】

参看JVM源码(参见附录2),可见这个优化同时试用于以下异常:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • ArrayIndexOutOfBoundsException
  • ArrayStoreException
  • ArithmeticException

相关核心代码片段:

代码语言:javascript
复制
  // If this throw happens frequently, an uncommon trap might cause
  // a performance pothole.  If there is a local exception handler,
  // and if this particular bytecode appears to be deoptimizing often,
  // let us handle the throw inline, with a preconstructed instance.
  // Note:   If the deopt count has blown up, the uncommon trap
  // runtime is going to flush this nmethod, not matter what.
  if (treat_throw_as_hot
      && (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {
    // If the throw is local, we use a pre-existing instance and
    // punt on the backtrace.  This would lead to a missing backtrace
    // (a repeat of 4292742) if the backtrace object is ever asked
    // for its backtrace.
    // Fixing this remaining case of 4292742 requires some flavor of
    // escape analysis.  Leave that for the future.
    ciInstance* ex_obj = NULL;
    switch (reason) {
    case Deoptimization::Reason_null_check:
      ex_obj = env()->NullPointerException_instance();
      break;
    case Deoptimization::Reason_div0_check:
      ex_obj = env()->ArithmeticException_instance();
      break;
    case Deoptimization::Reason_range_check:
      ex_obj = env()->ArrayIndexOutOfBoundsException_instance();
      break;
    case Deoptimization::Reason_class_check:
      if (java_bc() == Bytecodes::_aastore) {
        ex_obj = env()->ArrayStoreException_instance();
      } else {
        ex_obj = env()->ClassCastException_instance();
      }
      break;
    default:
      break;
    }

参考:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-03-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档