2014-01-15 4 views
4

try/catch 내부에서 사용하거나 try/catch 내부에서 사용하는 올바른 방법은 무엇입니까? 내 관점에서sqlConnection/명령문 + try/catch 블록을 사용하는 명령

using (SqlConnection connection = CreateSqlConnection(connString)) 
{ 
       using (SqlCommand command = CreateSqlCommand() 
       { 
        try{//open connection + execute command + do something else} 
        catch{//do something} 
       } 
} 

try 
{ 
    using (SqlConnection connection = CreateSqlConnection(connString)) 
    { 
       using (SqlCommand command = CreateSqlCommand() 
       { 
        //open connection + execute command + do something else 
       } 
    } 
} 
catch 
{ 
//do something 
} 

답변

5

:

try 
{ 
    using (SqlConnection connection = CreateSqlConnection(connString)) 
    { 
       using (SqlCommand command = CreateSqlCommand() 
       { 
        //open connection + execute command + do something else 
       } 
    } 
} 
catch 
{ 
//do something 
} 

위는 올바른 방법입니다.

데이터베이스에 대한 연결 예외가있는 경우이 방법을 사용하면 캐치 블록 내부에 걸릴 수 있습니다. 그러나 첫 번째 방법을 사용하면 그렇지 않습니다.

+0

을 원하는대로 예외를 처리 할 수 ​​있지만, 사용 한 Statment 자체가 의문이다, 그것을 행동을 나던 try, catch 및 finally 함수와 유사합니까? 그렇다면 사용 기능을 랩 할 필요가 있습니까? – lemunk

+0

그러나 이것은 반대하지 않습니다.'try {using (...) {try {}}}'. 또한, ** 연결 문을 **에서'using' 문과 외부가 아닌 다른 곳에서 여는 것이므로,'Try-Catch'를 사용하여 그 자체를 사용하는 것이 왜 다른 범위입니까? 나쁜 것을 너무 많이 잡을 위험에 처해 있습니다. –

+0

하지만 내 관점에서 위의 하나에서 선택의 incase 두 번째는 더 낫다. –

1

두 경우 모두 오류 발생시 처분 할 수있는 리소스를 닫습니다.

try-catch-statement를 두는 위치는 정보로 무엇을하고 싶은지에 달려 있습니다. 즉, SqlCommand 자체 또는 더 일반적인 SQL 오류와 관련된 오류에 대응하려는 경우 연결. 개인적으로

1

, 내가 가장 좋은 방법은 생각 - 다음 연결에 관계없이 닫히고 내가 또한 동의

using (SqlConnection connection = CreateSqlConnection(connString)) 
{ 
    using (SqlCommand command = CreateSqlCommand()) 
    { 
      try { //open connection, execute } 
      catch { // log and handle exception } 
      finally { // check connection state and close if required } 
    } 
}