C #에서 최종적으로 사용하는 이유는 무엇입니까?
finally 블록 안에 무엇이 있든 항상 (거의) 실행되므로 코드를 묶거나 닫지 않는 것의 차이점은 무엇입니까?
finally 블록 내부의 코드는 예외가 있는지 여부에 관계없이 실행됩니다. 이것은 항상 연결을 닫는 것처럼 실행해야하는 특정 하우스 키핑 기능에 매우 유용합니다.
자, 당신의 질문이 당신이 이것을 해야하는 이유 라고 생각 합니다.
try
{
doSomething();
}
catch
{
catchSomething();
}
finally
{
alwaysDoThis();
}
당신이 할 수있을 때 :
try
{
doSomething();
}
catch
{
catchSomething();
}
alwaysDoThis();
대답은 catch 문 내부의 코드가 많은 경우 예외를 다시 발생 시키거나 현재 함수에서 벗어날 것입니다. 후자의 코드에서 "alwaysDoThis ();" catch 문 내의 코드가 반환을 발생 시키거나 새 예외를 throw하면 호출이 실행되지 않습니다.
try-finally를 사용하면 얻을 수있는 대부분의 장점이 이미 지적되었지만 다음 중 하나를 추가 할 것이라고 생각했습니다.
try
{
// Code here that might throw an exception...
if (arbitraryCondition)
{
return true;
}
// Code here that might throw an exception...
}
finally
{
// Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}
이 동작은 특히 블록 정리 (자원 처리)를 수행해야하는 경우와 같은 다양한 상황에서 매우 유용하지만, 이 경우 블록을 사용 하는 것이 더 좋습니다.
스트림 리더, db 요청 등과 같은 관리되지 않는 코드 요청을 사용할 때마다; 예외를 잡으려면 try catch finally를 사용하고 마지막으로 스트림, 데이터 리더 등을 닫으십시오. 오류가 발생하지 않을 때 연결이 닫히지 않으면 DB 요청으로 실제로 나쁜 것입니다.
SqlConnection myConn = new SqlConnection("Connectionstring");
try
{
myConn.Open();
//make na DB Request
}
catch (Exception DBException)
{
//do somehting with exception
}
finally
{
myConn.Close();
myConn.Dispose();
}
오류를 잡고 싶지 않다면
using (SqlConnection myConn = new SqlConnection("Connectionstring"))
{
myConn.Open();
//make na DB Request
myConn.Close();
}
오류가있는 경우 연결 개체가 자동으로 삭제되지만 오류를 캡처하지는 않습니다.
Because finally will get executed even if you do not handle an exception in a catch block.
Finally statements can execute even after return.
private int myfun()
{
int a = 100; //any number
int b = 0;
try
{
a = (5 / b);
return a;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return a;
}
// Response.Write("Statement after return before finally"); -->this will give error "Syntax error, 'try' expected"
finally
{
Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
}
Response.Write("Statement after return after finally"); // -->Unreachable code
}
finally
, as in:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
is a guaranteed opportunity to execute code after your try..catch
block, regardless of whether or not your try block threw an exception.
That makes it perfect for things like releasing resources, db connections, file handles, etc.
i will explain the use of finally with a file reader exception Example
- with out using finally
try{ StreamReader strReader = new StreamReader(@"C:\Ariven\Project\Data.txt"); Console.WriteLine(strReader.ReadeToEnd()); StreamReader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
in the above example if the file called Data.txt is missing, an exception will be thrown and will be handled but the statement called StreamReader.Close();
will never be executed.
Because of this resources associated with reader was never released.
- To solve the above issue, we use finally
StreamReader strReader = null; try{ strReader = new StreamReader(@"C:\Ariven\Project\Data.txt"); Console.WriteLine(strReader.ReadeToEnd()); } catch (Exception ex){ Console.WriteLine(ex.Message); } finally{ if (strReader != null){ StreamReader.Close(); } }
Happy Coding :)
Note: "@" is used to create a verbatim string, to avoid error of "Unrecognized escape sequence". The @ symbol means to read that string literally, and don't interpret control characters otherwise.
Say you need to set the cursor back to the default pointer instead of a waiting (hourglass) cursor. If an exception is thrown before setting the cursor, and doesn't outright crash the app, you could be left with a confusing cursor.
Sometimes you don't want to handle an exception (no catch block), but you want some cleanup code to execute.
For example:
try
{
// exception (or not)
}
finally
{
// clean up always
}
The finally block is valuable for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
Ahh...I think I see what you're saying! Took me a sec...you're wondering "why place it in the finally block instead of after the finally block and completely outside the try-catch-finally".
As an example, it might be because you are halting execution if you throw an error, but you still want to clean up resources, such as open files, database connections, etc.
Control Flow of the Finally Block is either after the Try or Catch block.
[1. First Code]
[2. Try]
[3. Catch]
[4. Finally]
[5. After Code]
with Exception 1 > 2 > 3 > 4 > 5 if 3 has a Return statement 1 > 2 > 3 > 4
without Exception 1 > 2 > 4 > 5 if 2 has a return statement 1 > 2 > 4
As mentioned in the documentation:
A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
It is also worth reading this, which states:
Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.
So it is clear that code which resides in a finally
clause will be executed even if a prior catch
clause had a return
statement.
참고URL : https://stackoverflow.com/questions/547791/why-use-finally-in-c
'Programing' 카테고리의 다른 글
객관적 c 암시 적 변환은 정수 정밀도 'NSUInteger'(일명 'unsigned long')를 'int'경고로 잃습니다. (0) | 2020.05.18 |
---|---|
밀리 초를 날짜로 변환 (jQuery / JavaScript) (0) | 2020.05.18 |
JavaScript에 논리적 xor가없는 이유는 무엇입니까? (0) | 2020.05.18 |
공백을 밑줄로 바꾸려면 어떻게해야합니까? (0) | 2020.05.18 |
JavaScript에서 객체 {}를 키-값 쌍의 배열 []으로 변환하는 방법 (0) | 2020.05.18 |