development

try / catch + 사용하여 올바른 구문

big-blog 2020. 5. 20. 08:19
반응형

try / catch + 사용하여 올바른 구문


어느 것:

using (var myObject = new MyClass())
{
   try
   {
      // something here...
   }
   catch(Exception ex)
   {
      // Handle exception
   }
}

또는

try
{
   using (var myObject = new MyClass())
   {
      // something here...
   }
}
catch(Exception ex)
{
   // Handle exception
}

나는 두 번째를 선호합니다. 객체 생성과 관련된 오류도 잡을 수 있습니다.


using 블록은 try / finally ( MSDN ) 의 구문 단순화 일 뿐이므로 개인적으로 다음을 수행 할 것입니다.하지만 두 번째 옵션과는 크게 다릅니다.

MyClass myObject = null;
try {
  myObject = new MyClass();
  //important stuff
} catch (Exception ex) {
  //handle exception
} finally {
  if(myObject is IDisposable) myObject.Dispose();
}

catch 문이 using 문에 선언 된 변수에 액세스해야하는 경우 inside가 유일한 옵션입니다.

catch 문에서 사용하기 전에 참조 된 객체가 필요하면 내부 옵션이 유일한 옵션입니다.

catch 문이 사용자에게 메시지를 표시하는 것과 같이 알 수없는 기간 동안 작업을 수행하고 그 전에 리소스를 폐기하려는 경우 외부 옵션이 가장 좋습니다.

이와 비슷한 scenerio가있을 때마다 try-catch 블록은 일반적으로 사용보다 콜 스택보다 다른 방법입니다. 메소드가 이와 같이 발생하는 예외를 처리하는 방법을 아는 것은 일반적이지 않습니다.

그래서 나의 일반적인 추천은 바깥에 있습니다.

private void saveButton_Click(object sender, EventArgs args)
{
    try
    {
        SaveFile(myFile); // The using statement will appear somewhere in here.
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

때에 따라 다르지. WCF (Windows Communication Foundation)를 사용하는 using(...) { try... }경우 프록시 입력 using문이 예외 상태 인 경우 (예 :이 프록시를 삭제하면 다른 예외가 발생 함) 제대로 작동하지 않습니다 .

Personally, I believe in minimal handling approach, i.e. handle only exception you are aware of at the point of execution. In other word, if you know that the initialization of a variable in using may throw a particular exception, I wrap it with try-catch. Similarly, if within using body something may happen, which is not directly related to the variable in using, then I wrap it with another try for that particular exception. I rarely use Exception in my catches.

But I do like IDisposable and using though so I maybe biased.


Both are valid syntax. It really comes down to what you want to do: if you want to catch errors relating to creating/disposing the object, use the second. If not, use the first.


There is one important thing which I'll call out here: The first one will not catch any exception arising out of calling the MyClass constructor.


If the object you are initializing in the Using() block might throw any exception then you should go for the second syntax otherwise both the equally valid.

In my scenario, I had to open a file and I was passing filePath in the constructor of the object which I was initializing in the Using() block and it might throw exception if the filePath is wrong/empty. So in this case, second syntax makes sense.

My sample code :-

try
{
    using (var obj= new MyClass("fileName.extension"))
    {

    }
}
catch(Exception ex)
{
     //Take actions according to the exception.
}

참고URL : https://stackoverflow.com/questions/4590490/try-catch-using-right-syntax

반응형