Programming

어설 션 사용시기 및 예외 사용시기

procodes 2020. 7. 26. 13:10
반응형

어설 션 사용시기 및 예외 사용시기


대부분의 경우 예외를 사용하여 코드에서 조건을 확인합니다. 어설 션을 사용하기에 적절한시기가 언제인지 궁금합니다.

예를 들어

Group group=null;
try{
    group = service().getGroup("abc");
}catch(Exception e){
    //I dont log error because I know whenever error occur mean group not found
}

if(group !=null)
{
    //do something
}

여기에 어설 션이 어떻게 적용되는지 나타낼 수 있습니까? 어설 션을 사용해야합니까?

프로덕션 코드에서 어설 션을 사용하지 않고 단위 테스트에서 어설 션 만 볼 수 있습니다. 나는 대부분의 경우 예외를 사용하여 위와 같은 검사를 수행 할 수 있다는 것을 알고 있지만 "전문적으로"하는 적절한 방법을 알고 싶습니다.


어설 션은 절대로 발생해서는 안되는 것을 확인하는 데 사용되고 예외는 발생하는 것을 확인하는 데 사용되어야합니다.

예를 들어, 함수가 0으로 나눌 수 있으므로 예외를 사용해야하지만 어설 션을 사용하여 하드 드라이브가 갑자기 사라지는 지 확인할 수 있습니다.

어설 션은 프로그램 실행을 중지하지만 예외로 인해 프로그램이 계속 실행됩니다.

참고 if(group != null)단지 조건부 즉, 주장하지 않습니다.


내 마음에서 (목록이 불완전하고 주석에 맞추기에는 너무 깁니다), 나는 말할 것입니다 :

  • 공개 또는 보호 된 메소드 및 생성자에 전달 된 매개 변수를 확인할 때 예외 사용
  • 사용자와 상호 작용할 때 또는 예외적 인 상황에서 클라이언트 코드가 복구 될 것으로 예상되는 경우 예외 사용
  • 발생할 수있는 문제를 해결하기 위해 예외 사용
  • 전제 조건, 사후 조건 및 개인 / 내부 코드의 변형을 확인할 때 어설 션 사용
  • 자신 또는 개발자 팀에 의견을 제공하기 위해 어설 션 사용
  • 일어날 가능성이 거의없는 것을 확인할 때 어설 션을 사용하십시오. 그렇지 않으면 애플리케이션에 심각한 결함이 있음을 의미합니다.
  • use assertions to state things that you (supposedly) know to be true

In other words, exceptions address the robustness of your application while assertions address its correctness.

Assertions are designed to be cheap to write, you can use them almost everywhere and I'm using this rule of thumb: the more an assertion statement looks stupid, the more valuable it is and the more information it embeds. When debugging a program that does not behave the right way, you will surely check the more obvious failure possibilities based on your experience. Then you will check for problems that just cannot happen: this is exactly when assertions help a lot and save time.


Remember assertions can be disabled at runtime using parameters, and are disabled by default, so don't count on them except for debugging purposes.

또한 assert 를 사용하거나 사용하지 않는 추가 사례를 보려면 assert대한 Oracle 기사를 읽어야합니다 .


일반적으로 :

  • 내부 일관성 검사에 대해 어설 션을 사용하여 누군가 전원을 끄면 문제가되지 않습니다. ( java명령은 기본적으로 모든 어설 션을 해제합니다.)
  • 꺼서는 안되는 모든 종류의 검사에 대해 정기적 인 테스트를 사용하십시오. 여기 에는 버그로 인한 잠재적 손상을 방지 하는 방어 점검 및 사용자 또는 외부 서비스가 제공 한 모든 검증 데이터 / 요청 / 무엇이 포함됩니다.

귀하의 질문에 대한 다음 코드는 스타일이 좋지 않으며 잠재적으로 버그가 있습니다.

try {
    group = service().getGroup("abc");
} catch (Exception e) {
    //i dont log error because i know whenever error occur mean group not found
}

The problem is that you DON'T know that an exception means that the group was not found. It is also possible that the service() call threw an exception, or that it returned null which then caused a NullPointerException.

When you catch an "expected" exception, you should catch only the exception that you are expecting. By catching java.lang.Exception (and especially by not logging it), you are making it harder to diagnose / debug the problem, and potentially allowing the app to do more damage.


According to this doc http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html#design-faq-general, "The assert statement is appropriate for nonpublic precondition, postcondition and class invariant checking. Public precondition checking should still be performed by checks inside methods that result in particular, documented exceptions, such as IllegalArgumentException and IllegalStateException."

If you want to know more about precondition, postcondition and class invariant, check this doc: http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html#usage-conditions. It also contains with examples of assertions usage.


Well, back at Microsoft, the recommendation was to throw Exceptions in all APIs you make available publicly and use Asserts in all sorts of assumptions you make about code that's internal. It's a bit of a loose definition but I guess it's up to each developer to draw the line.

Regarding the use of Exceptions, as the name says, their usage should be exceptional so for the code you present above, the getGroup call should return null if no service exists. Exception should only occur if a network link goes down or something like that.

I guess the conclusion is that it's a bit left down to the development team for each application to define the boundaries of assert vs exceptions.


Testing for null will only catch nulls causing problems, whereas a try/catch as you have it will catch any error.

Broadly, try/catch is safer, but slightly slower, and you have to be careful that you catch all the kinds of error that may occur. So I would say use try/catch - one day the getGroup code may change, and you just might need that bigger net.


You can use this simple difference in mind while their usage. Exceptions will be used for checking expected and unexpected errors called checked and unchecked error while assertion is used mainly for debugging purposes at the run time to see whether the assumptions are validated or not.


I confess I'm a little confused by your question. When an assertion condition is not met, an exception is thrown. Confusingly this is called AssertionError. Note that it's unchecked, like (for example) IllegalArgumentException which is thrown in very similar circumstances.

So using assertions in Java

  1. is a more concise means of writing a condition/throw block
  2. permits you to turn these checks on/off via JVM parameters. Normally I would leave these checks on all the time, unless they impact runtime performance or have a similar penalty.

See section 6.1.2 (Assertions vs. other error code) of Sun's documentation at the following link.

http://www.oracle.com/technetwork/articles/javase/javapch06.pdf

This document gives the best advice I've seen on when to use assertions. Quoting from the document:

"A good rule of thumb is that you should use an assertion for exceptional cases that you would like to forget about. An assertion is the quickest way to deal with, and forget, a condition or state that you don’t expect to have to deal with."


Unfortunately asserts can be disabled. When in production you need all the help you can get when tracking down something unforeseen, so asserts disqualify themselves.

참고URL : https://stackoverflow.com/questions/1957645/when-to-use-an-assertion-and-when-to-use-an-exception

반응형