programing

NullPointer자바에 StackTrace과 예외.

kingscode 2022. 9. 2. 00:03
반응형

NullPointer자바에 StackTrace과 예외.

인스턴스가NullPointerException으로 StackTrace를 한다)를 StackTrace'를 호출한다)Throwable.printStackTrace() 다음과 같습니다: ) 、 [ 」

java.lang.NullPointerException

아무도 이거를 가로질러 들어왔나요?나는"java null포인터 빈 스택 추적"에 googling지만 이런 것을 가로질러 오지 않았다.

당신은 아마 최적화의 많은 수행하는 HotSpot JVM(태양 Microsystems, 나중에 오라클에 의해 구입된 것이 OpenJDK 원래, 부분)를 이용하고 있다. , 「다」를 건네야 .-XX:-OmitStackTraceInFastThrow 「」 「 JVM 」 。

그 최적화할 때 예외(일반적으로 NullPointer 있다.예외 탭을 처음, 전체 스택 추적과 포장 및 충전기 스택 추적(코드거나 위치를)을 기억하고 있다 인쇄된 것을 위해 발생한다.그 예외도 충분히 자주 발생한다,는 스택 추적 더 이상, 둘 다 더 나은 성능을 달성하기 그리고 동일한 스택 추적으로 통나무를 자주 홍수가 나지 않도록 인쇄되지 않는다.

이것이 어떻게 HotSpot JVM에서 구현된다 보려면, 그것을 복사하고, 전 세계 변수가 검색들 어서OmitStackTraceInFastThrow. 난 코드를(2019년에) 바라보며 지난 시간, 파일 graphKit.cpp에 있었다.

여러분이 논평에 언급했듯이 당신 log4j을 사용하고 있습니다.(불시에) 내가 쓴 곳을 발견했다

LOG.error(exc);

전형적인 것이 아니라

LOG.error("Some informative message", e);

게으름 때문인지 아니면 그냥 생각하지 않아서인지도 몰라요.여기서 아쉬운 점은 그것이 당신이 기대한 대로 작동하지 않는다는 것입니다.logger API는 실제로 문자열이 아닌 첫 번째 인수로 객체를 사용하고 그 인수로 String()을 호출합니다.따라서 멋진 스택트레이스를 얻는 대신 toString만 출력합니다.NPE의 경우 이 트레이스는 매우 쓸모가 없습니다.

아마 이게 당신이 겪고 있는 일인가요?

우리는 과거에 이와 같은 행동을 본 적이 있다. Null 가 Null Pointer의 Null Pointer가 Null Pointer의 Null Pointer로 판명되었습니다.후가 여러 번 했습니다.Log.error(String, Throwable)풀 스택 트레이스 포함을 정지합니다.

로그에서 더 먼 곳을 찾아보세요.범인을 찾을 수 있을지도 몰라요.

편집: 버그는 관련이 있는 것 같습니다만, 너무 오래전에 수정되어 원인은 아닐지도 모릅니다.

Here is an explanation : Hotspot caused exceptions to lose their stack traces in production – and the fix

I've tested it on Mac OS X

  • java version "1.6.0_26"
  • Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
  • Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)

    Object string = "abcd";
    int i = 0;
    while (i < 12289) {
        i++;
        try {
            Integer a = (Integer) string;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

For this specific fragment of code, 12288 iterations (+frequency?) seems to be the limit where JVM has decided to use preallocated exception...

exception.toString does not give you the StackTrace, it only returns

a short description of this throwable. The result is the concatenation of:

* the name of the class of this object
* ": " (a colon and a space)
* the result of invoking this object's getLocalizedMessage() method

Use exception.printStackTrace instead to output the StackTrace.

Alternate suggestion - if you're using Eclipse, you could set a breakpoint on NullPointerException itself (in the Debug perspective, go to the "Breakpoints" tab and click on the little icon that has a ! in it)

Check both the "caught" and "uncaught" options - now when you trigger the NPE, you'll immediately breakpoint and you can then step through and see how exactly it is handled and why you're not getting a stack trace.

toString()는 예외명과 옵션메시지만 반환합니다.전화할 것을 제안합니다.

exception.printStackTrace()

to dump the message, or if you need the gory details:

 StackTraceElement[] trace = exception.getStackTrace()

This will output the Exception, use only to debug you should handle you exceptions better.

import java.io.PrintWriter;
import java.io.StringWriter;
    public static String getStackTrace(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        t.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

(코드가 호출하고 있는지 여부에 대한 질문은 아직 불명확합니다.printStackTrace()또는 로깅 핸들러에 의해 실행됩니다).

Here are some possible explanations about what might be happening:

  • The logger / handler being used has been configured to only output the exception's message string, not a full stack trace.

  • 응용 프로그램(또는 일부 서드파티 라이브러리)이 다음을 사용하여 예외를 로깅하고 있습니다.LOG.error(ex);(예를 들어) log4j Logger 메서드의 2-argument 형식이 아닌

  • The message is coming from somewhere different to where you think it is; e.g. it is actually coming some third-party library method, or some random stuff left over from earlier attempts to debug.

  • The exception that is being logged has overloaded some methods to obscure the stacktrace. If that is the case, the exception won't be a genuine NullPointerException, but will be some custom subtype of NPE or even some unconnected exception.

저는 가능한 마지막 설명이 거의 불가능하다고 생각합니다만, 사람들은 적어도 리버스 엔지니어링을 "예방"하기 위해 이런 종류의 일을 하는 것을 고려합니다.물론 그것은 정직한 개발자들의 삶을 어렵게 만드는 데만 성공한다.

프로젝트에서 AspectJ를 사용하는 경우 일부 AspectJ가 스택 트레이스의 일부를 숨길 수 있습니다.예를 들어, 오늘은 다음과 같은 일이 있었습니다.

java.lang.NullPointerException:
  at com.company.product.MyTest.test(MyTest.java:37)

이 스택 트레이스는 Maven의 Surefire를 통해 테스트를 실행할 때 인쇄되었습니다.

한편 IntelliJ에서 테스트를 실행하면 다른 스택트레이스가 출력되었습니다

java.lang.NullPointerException
  at com.company.product.library.ArgumentChecker.nonNull(ArgumentChecker.java:67)
  at ...
  at com.company.product.aspects.CheckArgumentsAspect.wrap(CheckArgumentsAspect.java:82)
  at ...
  at com.company.product.MyTest.test(MyTest.java:37)

언급URL : https://stackoverflow.com/questions/2411487/nullpointerexception-in-java-with-no-stacktrace

반응형