2011-09-16 9 views
4

Windows 양식 응용 프로그램에서 직접 예외를 만들려고합니다. 일부 데이터를 데이터베이스에 추가하려고합니다.C에서 사용자 지정 예외를 만드는 방법

코드 : 여기

try 
{ 
    string insertData = string.Format("INSERT INTO " + constants.PIZZABROADCASTTABLE + 
     " VALUES(@starttime,@endtime,@lastupdatetime,@applicationname)"); 
    sqlCommand = new SqlCommand(insertData, databaseConnectivity.connection); 
    sqlCommand.Parameters.AddWithValue("@starttime", broadcastStartDateTime); 
    sqlCommand.Parameters.AddWithValue("@endtime", broadcastEndDateTime); 
    sqlCommand.Parameters.AddWithValue("@lastuptime", currentDateTime); 
    sqlCommand.Parameters.AddWithValue("@applicationname", txtApplicationName.Text); 
    sqlCommand.ExecuteNonQuery(); 
} 
catch (DataBaseException ex) 
{ 
    MessageBox.Show(ex.Message); 
} 

난 내 자신의 예외를 만들었습니다. 여기에 @lastupdatetime 대신 SqlException을 캡처하는 스칼라 변수 @lastuptime이 주어졌습니다.

여기에 내 DatabaseException 클래스가 있습니다.

class DataBaseException : Exception 
{ 
    public DataBaseException(string Message) 
     : base(Message) 
    { 

    } 
    public DataBaseException(string message, Exception innerException) 
     : base(message, innerException) 
    { 
    } 
} 

다음은 프로그램을 실행하는 동안이

sqlCommand.ExecuteQuery(); 

에서 오류를 표시하지만 오류를 캡처하고 메시지 상자의 텍스트가 표시되지 않습니다. 나는 내가 잘못한 것을 알고있다. 나는 사용자 정의 예외 처리를 만든 것이 옳은 것인지 잘못되었는지를 모른다.

아무도 도와 줄 수 있습니까? 미리 감사드립니다.

+0

또한 예외를 [Serializable]로 표시하고 두 개의 생성자 (직렬화를위한 인수가 아닌 생성자 및 사용자 정의 직렬화를위한 인수로 SerializationInfo 및 StreamingContext가있는 생성자)를 추가해야합니다. – Daniel

답변

2

호출하는 메서드에서 catch 할 수 있도록 사용자 지정 예외를 throw해야합니다. 당신의 코드에서, 프로그램은 DB로부터 예외를 던지며 사용자 정의 예외는 발생시키지 않습니다.

void UpdateDatabase() 
{ 
//... 
     try 
      { 

      } 
       // Your checks to identify - type of exception 
       // ... 
       // .net exception 
       // Throw your custom exception in the appropriate block - 
       // throw new DatabaseException(); 
      catch (OutOfMemoryException ex1) 
      { 

      } 
      catch (InvalidDataException ex2) 
      { 

      } 
      // Generic exception 
      catch (Exception ex3) 
      { 
       // throw new DatabaseException(); 
      } 
//.... 
} 

// Method calling UpdateDatabase need to handle Custom exception 
void CallUpdateDatabase() 
{ 
try 
    { 
    UpdateDatabase(); 
    } 
    catch(DatabaseException dbEx) 
    { 
    // Handle your custom exception 
    } 
} 
+2

내부 예외를 유지할 수 있도록 예외 객체를 사용하는 생성자를 제공 할 수 있습니다. –

+0

catch의 예외 유형을 알고 if 문에서 유형을 확인하지 않고 구체적으로 catch하는 경우 (catch (DatabaseException de) {} catch (SQLiteException) {} catch (NullRefer .. –

0

생성 한 DatabaseException이 SqlCommand 속성과 메서드에서 throw되지 않습니다. 따라서 캐치가 실행되지 않습니다.

Exception DatabaseException을 작성하여 호출했다고해서 모든 "데이터베이스"코드가 이제 예외를 던질 것을 의미하지는 않습니다. SqlCommand가 작성되면 매우 특정한 예외 집합을 던지도록 작성되었습니다. SqlCommand와 그 메소드가 MSDN에 던져 놓은 예외 목록을 찾을 수 있습니다.

내 답변이 당신에게 이해가되지 않는 경우 알려주십시오.

0

자신의 예외는 괜찮지 만 Sql.ExecuteQuery, 당신은 같은 것을 할 수있는 SQLException을 발생합니다

void CallDatabase(/* your parameters */) 
{ 
    try 
    { 
     string insertData = string.Format("INSERT INTO " + constants.PIZZABROADCASTTABLE + " VALUES(@starttime,@endtime,@lastupdatetime,@applicationname)"); 
     sqlCommand = new SqlCommand(insertData, databaseConnectivity.connection); 
     sqlCommand.Parameters.AddWithValue("@starttime", broadcastStartDateTime); 
     sqlCommand.Parameters.AddWithValue("@endtime", broadcastEndDateTime); 
     sqlCommand.Parameters.AddWithValue("@lastuptime", currentDateTime); 
     sqlCommand.Parameters.AddWithValue("@applicationname", txtApplicationName.Text); 
     sqlCommand.ExecuteNonQuery(); 

    } 
    catch (SqlException ex) 
    { 
     throw new DataBaseException("Database error", ex); 
    } 
} 

/* somewhere in your code */ 
try 
{ 
    CallDatabase(...); 
} 
catch (DataBaseException ex) 
{ 
    MessageBox.Show(ex.Message); 
} 
0

이 내가이 루틴 (다소)를 작성합니다 방법입니다. 여기에 던져 클래스와

try 
    { 
     string insertData = string.Format("INSERT INTO " + constants.PIZZABROADCASTTABLE + " VALUES(@starttime,@endtime,@lastupdatetime,@applicationname)"); 
     using (sqlCommand = new SqlCommand(insertData, databaseConnectivity.connection)) 
     { 
      sqlCommand.Parameters.AddWithValue("@starttime", broadcastStartDateTime); 
      sqlCommand.Parameters.AddWithValue("@endtime", broadcastEndDateTime); 
      sqlCommand.Parameters.AddWithValue("@lastuptime", currentDateTime); 
      sqlCommand.Parameters.AddWithValue("@applicationname", txtApplicationName.Text); 

      sqlCommand.ExecuteNonQuery(); 
     } 
    } 
    catch (Exception ex) 
    { 
     string s = "Failed to insert into table " + constants.PIZZABROADCASTTABLE + "Database Error! " + Environment.NewLine + "Details: " + ex.ToString(); 
     MessageBox.Show(s, MessageBoxButtons.OK, MessageBoxIcons.Error); 
     // Or 
     //throw new DatabaseException(s, ex); 
    } 
    finally 
    { 
     if (databaseConnectivity != null && databaseConnectivity.connection != null) 
      databaseConnectivity.connection.Close(); 
     else 
      MessageBox.Show("No database connectivity!", "Error", MessageBoxButtons.OK, MessageBoxIcons.Error); 
    } 
관련 문제