IT박스

“어설 션”키워드는 무엇을합니까?

itboxs 2020. 6. 26. 19:06
반응형

“어설 션”키워드는 무엇을합니까? [복제]


이 질문에는 이미 답변이 있습니다.

무엇을 assert합니까? 예를 들어 함수에서 :

private static int charAt(String s, int d) {
    assert d >= 0 && d <= s.length();
    if (d == s.length()) return -1;
    return s.charAt(d);
}

당신이 -enableassertions(또는 -ea짧게) 프로그램을 시작하면 이 진술

assert cond;

에 해당

if (!cond)
    throw new AssertionError();

이 옵션없이 프로그램을 시작하면 assert 문이 적용되지 않습니다.

예를 들어, assert d >= 0 && d <= s.length();귀하의 질문에 게시 된 것처럼

if (!(d >= 0 && d <= s.length()))
    throw new AssertionError();

( -enableassertions그것으로 시작한 경우 입니다.)


공식적으로 Java 언어 사양 : 14.10. assert문은 다음을 말한다 :

14.10. assert
의 주장은이다 assert부울 식을 포함하는 문. 어설 션이 활성화 또는 비활성화되었습니다 . 어설 션이 활성화 된 경우 어설 션을 실행하면 부울 식이 평가되고식이로 평가되면 오류가보고 됩니다 false. 어설 션이 비활성화 된 경우 어설 션 실행은 아무런 영향을 미치지 않습니다.

어디 "활성화 또는 비활성화" 으로 제어 -ea스위치 "오류가보고됩니다" 는 것을 의미 AssertionError슬로우됩니다.


그리고 마지막으로 덜 알려진 기능 assert:

다음 : "Error message"과 같이 추가 할 수 있습니다 .

assert d != null : "d is null";

던진 AssertionError의 오류 메시지를 지정합니다.


이 게시물은 여기 기사로 다시 작성되었습니다 .


조건이 충족되지 않으면가 AssertionError발생합니다.

그러나 어설 션을 활성화해야합니다. 그렇지 않으면 assert표현은 아무것도하지 않습니다. 보다:

http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable


assertAssertionFailed조건이 true가 아닌 경우 프로그램에서 예외 를 발생시키는 디버깅 도구입니다 . 이 경우 다음 두 조건 중 하나가 false로 평가되면 프로그램에서 예외가 발생합니다. 일반적으로 assert프로덕션 코드에서는 사용 하면 안됩니다


이 문서에 대한 많은 문서를 읽었지만 어떻게, 언제, 어디서 사용하는지 혼란 스럽습니다.

이해하기가 매우 간단합니다.

이와 비슷한 상황이 발생하면

    String strA = null;
    String strB = null;
    if (2 > 1){
        strA = "Hello World";
    }

    strB = strA.toLowerCase(); 

strA가 strB에 NULL 값을 생성 할 수 있다는 경고 (strB = strA.toLowerCase ();에 노란색 선 표시)가 표시 될 수 있습니다. strB가 결국 null이 아니라는 것을 알고 있지만, 경우에 따라 assert를 사용합니다.

1. 경고를 비활성화하십시오.

2. 예외가 발생하면 최악의 상황이 발생하면 (응용 프로그램을 실행할 때)

때로는 코드를 컴파일 할 때 결과를 얻지 못하고 버그입니다. 그러나 응용 프로그램은 중단되지 않으며이 버그의 원인을 찾는 데 매우 많은 시간을 소비합니다.

따라서 다음과 같이 주장을한다면 :

    assert strA != null; //Adding here
    strB = strA .toLowerCase();

strA가 절대적으로 null 값이 아니라고 컴파일러에게 알려 주면 경고를 '평화롭게'끌 수 있습니다. NULL 인 경우 (가장 최악의 경우) 응용 프로그램을 중지하고 버그를 찾아서 찾습니다.


Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.

JavaDoc


Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.

In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.


It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError.

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10


Assert does throw an AssertionError if you run your app with assertions turned on.

int a = 42;
assert a >= 0 && d <= 10;

If you run this with, say: java -ea -jar peiska.jar

It shall throw an java.lang.AssertionError

참고URL : https://stackoverflow.com/questions/3018683/what-does-the-assert-keyword-do

반응형