Program Club

'catch'블록없이 'try-finally'블록 사용

proclub 2020. 11. 14. 11:15
반응형

'catch'블록없이 'try-finally'블록 사용


try-finally블록이없는 블록 을 사용하는 것이 적절한 상황이 catch있습니까?


try콘텐츠 이후 또는 예외에서 일부 작업이 발생하도록하는 데 사용 하지만 해당 예외를 사용하지 않으려는 경우에 사용합니다.

분명히 말하면 예외를 숨기지 않습니다. finally예외 호출 스택을 전파하기 전에 블록이 실행됩니다.

또한 using키워드 를 사용할 때 실수로 사용합니다 . 왜냐하면 이것은 try-finally(정확한 변환은 아니지만 인수를 위해 충분히 가깝습니다) 로 컴파일되기 때문 입니다.

try
{
    TrySomeCodeThatMightException();
}
finally
{
    CleanupEvenOnFailure();
}

에서 실행되는 코드가 실행 finally된다는 보장은 없지만 보장되지 않는 경우는 상당히 우월합니다. 기억조차 할 수 없습니다. 내가 기억하는 것은 만약 당신이 그 경우라면, 실행 finally하지 않는 것이 당신의 가장 큰 문제가 아닐 가능성이 매우 높다는 것입니다 :-) 기본적으로 그것을 땀을 흘리지 마십시오.

Tobias에서 업데이트 : finally 프로세스가 종료되면 실행되지 않습니다.

Paddy에서 업데이트 : .net try..finally 블록에서 최종적으로 실행되지 않는 조건

가장 일반적인 예는 코드가 실패하더라도 데이터베이스 연결 또는 외부 리소스를 폐기하는 것입니다.

using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-)
{
    // Do stuff.
}

다음 과 같이 컴파일됩니다 .

SqlConnection conn;

try
{
    conn = new SqlConnection("");
    // Do stuff.
}
finally
{
    if (conn != null)
        conn.Dispose();
}

using동일 try-finally합니다. try-finally내부 청소를 원할 때만 사용 finally하고 예외는 신경 쓰지 않습니다.

가장 좋은 방법은 될 것입니다

try
{
   using(resource)
   {
       //Do something here
   }   
}catch(Exception)
{
     //Handle Error
}

이렇게하면 정리가 using실패해도 코드가 실패하지 않습니다.

finally실행되지 않는 몇 가지 조건이 있습니다 .

  • 어떤이있는 경우 StackOverflowExceptionExecutingEngineException.
  • 프로세스가 외부 소스에서 종료됩니다.

이것이 당신의 의심에 답하기를 바랍니다.


예를 들어 try 블록에서 만들고 사용하는 관리되지 않는 리소스가있는 경우 finally 블록을 사용하여 해당 리소스를 해제 할 수 있습니다. finally 블록은 try 블록에서 일어나는 일 (예 : 예외)에도 불구하고 항상 실행됩니다.

예를 들어 lock (x) 문은 실제로 다음과 같습니다.

System.Threading.Monitor.Enter(x); 
try { ... } 
finally 
{ 
    System.Threading.Monitor.Exit(x); 
} 

finally 블록은 항상 배타적 잠금이 해제되었는지 확인하기 위해 호출됩니다.


코드를 사용한 좋은 설명 :

void MyMethod1()
{
    try
    {
        MyMethod2();
        MyMethod3();
    }
    catch(Exception e)
    {
        //do something with the exception
    }
}


void MyMethod2()
{
    try
    {
        //perform actions that need cleaning up
    }
    finally
    {
        //clean up
    }
}


void MyMethod3()
{
    //do something
}

If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

http://forums.asp.net/t/1092267.aspx?Try+without+Catch+but+with+finally+doesn+t+throw+error+Why+no+syntax+error+


You need a finally block, when no matter which (if any) exceptions are caught or even if none are caught you still want to execute some code before the block exits. For instance, you might want to close an open file.

See Also try-finally


try/finally: when you do not want to handle any exceptions but want to ensure some action(s) occur whether or not an exception is thrown by called code.


Here is a situation where you might want to use try finally: when you would normally use a using statement, but can't because you are calling a method by reflection.

This won't work

using (objMsg  =  Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("omApp.MessagingBO")))
{

}

instead use

           object objMsg = null;
            try
            {
                objMsg
                   = Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("myAssembly.objBO"));

                strResponse = (string)objMsg.GetType().InvokeMember("MyMethod", BindingFlags.Public
                        | BindingFlags.Instance | BindingFlags.InvokeMethod, null, objMsg,
                        new object[] { vxmlRequest.OuterXml });
            }               
            finally
            {
                if (objMsg!=null)
                    ((IDisposable)objMsg).Dispose();
            }

Have a look at the following link: https://softwareengineering.stackexchange.com/questions/131397/why-use-try-finally-without-a-catch-clause

It depends on the architecture of your application and the operation you are performing in the block.


I don't know anything about C#, but it seems that anything you could do with a try-finally, you could more elegantly do with a using statement. C++ doesn't even have a finally as a result of its RAII.


Here's a use case that I always (uhm..) use:

int? x; //note the nullable type here!
try
{
    x = int.Parse(someString);
}
catch { } //don't care, let it just be null

1.we can use the try block without catch but we should use the catch/finally, any one of them. 2.We can't use only try block.

참고URL : https://stackoverflow.com/questions/9291437/use-a-try-finally-block-without-a-catch-block

반응형