Programing

Java 스타일을 사용하는 방법은 C #에서 키워드를 던지나요?

lottogame 2020. 10. 9. 08:45
반응형

Java 스타일을 사용하는 방법은 C #에서 키워드를 던지나요?


Java에서 throws키워드는 메소드가 자체적으로 예외를 처리하지 않고 호출하는 메소드에 던지도록 선언 할 수 있도록합니다.

C #에 유사한 키워드 / 속성이 있습니까?

동등한 효과가없는 경우 어떻게 동일한 (또는 유사한) 효과를 얻을 수 있습니까?


Java에서는 예외를 처리하거나 throws키워드를 사용하여 예외를 throw 할 수있는 것으로 메소드를 표시해야합니다 .

C #에는이 키워드 또는 이에 상응하는 키워드가 없습니다. C #에서와 같이 예외를 처리하지 않으면 잡히거나 잡히지 않으면 프로그램이 종료됩니다.

처리하려면 다음을 수행하십시오.

try
{
  // code that throws an exception
}
catch(ArgumentNullException ex)
{
  // code that handles the exception
  throw;
}

op는 키워드가 아닌 Java의 throws절에 해당 하는 C # 에 대해 묻습니다 throw. 이것은 확인 된 예외가 발생할 수 있음을 나타 내기 위해 Java의 메소드 서명에서 사용됩니다.

C #에는 Java 검사 예외와 직접적으로 동등한 것이 없습니다. C #에는 동등한 메서드 서명 절이 없습니다.

// Java - need to have throws clause if IOException not handled
public void readFile() throws java.io.IOException {
  ...not explicitly handling java.io.IOException...
}

번역하다

// C# - no equivalent of throws clause exceptions are unchecked
public void ReadFile() 
{
  ...not explicitly handling System.IO.IOException...
}

예, 이것은 오래된 스레드이지만 답변을 검색 할 때 자주 오래된 스레드를 찾아서 내가 찾은 유용한 것을 추가 할 것이라고 생각했습니다.

Visual Studio 2012를 사용하는 경우 IDE 수준 "반복"에 해당하는 것을 허용하는 데 사용할 수있는 기본 제공 도구가 있습니다.

당신이 사용하는 경우 XML 문서의 댓글 , 위에서 언급 한 바와 같이, 당신은 사용할 수 있습니다 <예외> 왜가 발생하면 나에 대한 정보뿐만 아니라 메소드 또는 클래스에 의해 발생한 예외의 유형을 지정하는 태그를.

예:

    /// <summary>This method throws an exception.</summary>
    /// <param name="myPath">A path to a directory that will be zipped.</param>
    /// <exception cref="IOException">This exception is thrown if the archive already exists</exception>
    public void FooThrowsAnException (string myPath)
    {
        // This will throw an IO exception
        ZipFile.CreateFromDirectory(myPath);
    }

다음은 bytes.com에서 자금을 지원하는 비슷한 질문에 대한 답변입니다 .

짧은 대답은 '아니요'입니다. C #에는 확인 된 예외가 없습니다. 언어 디자이너는이 인터뷰에서이 결정에 대해 논의합니다.

http://www.artima.com/intv/handcuffs.html

가장 가까운 방법은 XML 문서의 태그를 사용하고 NDoc에서 생성 한 문서를 코드 / 어셈블리와 함께 배포하여 다른 사람들이 사용자가 던지는 예외를 볼 수 있도록하는 것입니다 (MS가 MSDN 문서에서 정확히 수행하는 작업). 처리되지 않은 예외에 대해 알려주기 위해 컴파일러에 의존 할 수는 없지만 Java에서 익숙 할 수 있습니다.


여기에서 대부분의 답변을 살펴본 후 몇 가지 생각을 추가하고 싶습니다.

  1. XML 문서 주석에 의존하고 다른 사람들이 의존하기를 기대하는 것은 좋지 않은 선택입니다. 필자가 접한 대부분의 C # 코드는 XML 문서 주석으로 메서드를 완전하고 일관되게 문서화하지 않습니다. 그리고 C #에서 예외를 확인하지 않으면 API 사용자가 모든 예외를 개별적으로 처리하는 방법을 알기 위해 메서드가 throw하는 모든 예외를 어떻게 문서화 할 수 있습니까? 구현에서 throw 키워드로 자신이 던지는 것들에 대해서만 알고 있다는 것을 기억하십시오. 메서드 구현 내에서 사용중인 API는 문서화되지 않았고 구현에서 처리하지 않기 때문에 알 수없는 예외를 throw 할 수 있으므로 호출자 앞에서 폭발 할 것입니다. 방법. 다시 말해,

  2. Andreas는 C # 디자인 팀이 확인 된 예외에 대해 결정한 이유에 대한 답변에서 Anders Hejlsberg와의 인터뷰를 연결했습니다. 원래 질문에 대한 궁극적 인 답변은 해당 인터뷰에 숨겨져 있습니다.

프로그래머는 어디에서나 try finally를 작성하여 코드를 보호하므로 예외가 발생하면 올바르게 되돌릴 수 있지만 실제로는 예외 처리에 관심이 없습니다.

다시 말해서, 항상 모든 곳에서 모든 예외를 포착 할 것이므로 특정 API에 대해 어떤 종류의 예외가 예상 될 수 있는지 아무도 관심이 없어야합니다. 그리고 특정 예외에 대해 정말로 관심을 갖고 싶다면이를 처리하는 방법은 Java throws 키워드와 같은 메소드 서명을 정의하는 사람이 아니라 API 사용자에게 특정 예외 처리를 강제하는 것이 아닙니다.

-

Personally, I'm torn here. I agree with Anders that having checked exceptions doesn't solve the problem without adding new, different problems. Just like with the XML documentation comments, I rarely see C# code with everything wrapped in try finally blocks. It feels to me though this is indeed your only option and something that seems like a good practice.


Actually not having checked exceptions in C# can be considered a good or bad thing.

I myself consider it to be a good solution since checked exceptions provide you with the following problems:

  1. Technical Exceptions leaking to the business/domain layer because you cannot handle them properly on the low level.
  2. They belong to the method signature which doesn't always play nice with API design.

Because of that in most bigger applications you will see the following pattern often when checked Exceptions occur:

try {
    // Some Code
} catch(SomeException ex){
    throw new RuntimeException(ex);
}

Which essentially means emulating the way C#/.NET handles all Exceptions.


You are asking about this :

Re-throwing an Exception

public void Method()
{
  try
  {
      int x = 0;
      int sum = 100/x;
  }
  catch(DivideByZeroException e)
  {
      throw;
  }
}

or

static void Main() 
    {
        string s = null;

        if (s == null) 
        {
            throw new ArgumentNullException();
        }

        Console.Write("The string s is null"); // not executed
    }

There are some fleeting similarities between the .Net CodeContract EnsuresOnThrow<> and the java throws descriptor, in that both can signal to the caller as the type of exception which could be raised from a function or method, although there are also major differences between the 2:

  • EnsuresOnThrow<> goes beyond just stating which exceptions can be thrown, but also stipulates the conditions under which they are guaranteed to be thrown - this can be quite onerous code in the called method if the exception condition isn't trivial to identify. Java throws provides an indication of which exceptions could be thrown (i.e. IMO the focus in .Net is inside the method which contracts to prove the throw, whereas in Java the focus shifts to the caller to acknowledge the possibility of the exception).
  • .Net CC doesn't make the distinction between Checked vs Unchecked exceptions that Java has, although the CC manual section 2.2.2 does mention to

"use exceptional postconditions only for those exceptions that a caller should expect as part of the API"

  • In .Net the caller can determine whether or not to do anything with the exception (e.g. by disabling contracts). In Java, the caller must do something, even if it adds a throws for the same exception on its interface.

Code Contracts manual here

참고URL : https://stackoverflow.com/questions/3465465/how-to-use-java-style-throws-keyword-in-c

반응형