2014-03-05 6 views
0

나는 간단한 애플리케이션을 사용하고 있으며 오류를 정상적으로 처리하려고합니다.오류 및 예외 처리

나는 그냥 잡으려고하지 않습니다. 나는 C#을 사용하기 위해 학교에 가기 전에 파이썬을 배우기 시작했다. 내 코드는 다음과 같습니다.

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using System.Text; 
using System.Threading.Tasks; 

namespace Crud 
{ 
    class Program 
    { 
     static string conn_string = "Data Source=MY_SQLSERVER;Initial Catalog=A_DATABASE"; 

     private static void Create(string name, string email) 
     { 
      using (SqlConnection conn = new SqlConnection(conn_string)) 
      { 
       SqlCommand cmd = conn.CreateCommand(); 

       cmd.CommandText = @"INSERT INTO dbo.Person (name, email) 
            VALUES (@name, @email)"; 
       cmd.Parameters.AddWithValue("@name", name); 
       cmd.Parameters.AddWithValue("@email", email); 
       conn.Open(); 
       cmd.ExecuteNonQuery(); 
       conn.Close(); 
      } 
     } 

     private static void Read() 
     { 
      using (SqlConnection conn = new SqlConnection(conn_string)) 
      { 
       SqlCommand cmd = conn.CreateCommand(); 
       cmd.CommandText = @"SELECT id, name, email FROM dbo.Person ORDER BY id"; 
       conn.Open(); 

       using (SqlDataReader dr = cmd.ExecuteReader()) 
       { 
        while (dr.Read()) 
         Console.WriteLine("{0}\t{1}\t{2}", dr.GetInt32(0), dr.GetString(1), dr.GetString(2)); 
       } 
       conn.Close(); 
      } 
     } 


     private static void Update(int id, string name, string email) 
     { 
      using (SqlConnection conn = new SqlConnection(conn_string)) 
      { 
       SqlCommand cmd = conn.CreateCommand(); 

       cmd.CommandText = @"UPDATE dbo.Person SET [email protected], [email protected] 
            WHERE id = @id"; 
       cmd.Parameters.AddWithValue("@id", id); 
       cmd.Parameters.AddWithValue("@name", name); 
       cmd.Parameters.AddWithValue("@email", email); 
       conn.Open(); 
       cmd.ExecuteNonQuery(); 
       conn.Close(); 
      } 
     } 

     private static void Delete(int id) 
     { 
      using (SqlConnection conn = new SqlConnection(conn_string)) 
      { 
       SqlCommand cmd = conn.CreateCommand(); 

       cmd.CommandText = @"DELETE FROM dbo.Person WHERE [email protected]"; 
       cmd.Parameters.AddWithValue("@id", id); 
       conn.Open(); 
       cmd.ExecuteNonQuery(); 
       conn.Close(); 
      } 
     } 

     static void Main(string[] args) 
     { 
      Console.WriteLine("Please Enter a Command (Create, Read, Update or Delete)"); 
      string input = Console.ReadLine(); 

      if (input == "Read" || input == "read") 
      { 
       Read(); 
       Console.WriteLine(""); 
      } 
      else if (input == "Create" || input == "create") 
      { 
       Console.WriteLine("Enter a name"); 
       string name = Console.ReadLine(); 
       Console.WriteLine("Enter an email address"); 
       string email = Console.ReadLine(); 

       Create(name, email); 
       // Assuming Create has not yet returned an error, everything successful 
       Console.WriteLine("Entry Created Successfully!"); 
      } 
      else if (input == "Update" || input == "update") 
      { 
       int id; 
       bool check; 
       do 
       { 
        Console.WriteLine("What id would you like to change?"); 
        string val = Console.ReadLine(); 
        check = int.TryParse(val, out id); 
       } while (!check); 
       Console.WriteLine("Enter a name"); 
       string name = Console.ReadLine(); 
       Console.WriteLine("Enter an email address"); 
       string email = Console.ReadLine(); 

       Update(id, name, email); 
       Console.WriteLine("Entry Updated Successfully!"); 
      } 
      else if (input == "Delete" || input == "delete") 
      { 
       int id; 
       bool check; 
       do 
       { 
        Console.WriteLine("What id would you like to delete?"); 
        string val = Console.ReadLine(); 
        check = int.TryParse(val, out id); 
       } while (!check); 

       Delete(id); 
       Console.WriteLine("Entry Deleted Successfully :("); 
      } 
     } 
    } 
} 

효과는 있지만 허약합니다. 이것은 언젠가 html 솔루션으로 바뀔 콘솔 앱입니다.하지만 ...

어디에서 try catch 블록을 넣을지 잘 모르겠습니다. 예외를 어디에 두어야할지 모르겠습니다. 그렇다면 나는 msdn에있어 그들은 그들이 마침내 사용한다고 말해. 마침내, 내가 이해할 수있는 무엇인가. 그래서 파이썬에서 오는 것은 try가 분명히 똑같다고 말하고 싶습니다. 예를 들어 catch(){}은 날카로운 데 except:과 비슷하지만 파이썬을 제외하고는 인수를 사용하지 않았습니다. 나는 그런 멍청한 녀석이다. .NET에서 Exception 객체를 사용할 수 있다고 생각하지만 필요하지 않습니다. 난 그냥 오류가 발생하면 사용자 정의 메시지를 쓰고 싶다 ... 내 말은, 얼마나 힘들어 href 작성입니까? 나는 제대로 작동하지 못합니다.

그럼 내 질문은 어떻게 구성 할까? Create 메서드를 사용하면 각 무거운 작업 내에서 try catch 블록을 유지하고 싶습니다.

답변

3

기본 C# 예외 처리 다음 catch 블록은 위의 예에서 모든 예외를 잡을 것

try 
{ 
    //do stuff 
} 
catch 
{ 
    //write custom exception message 
} 
finally 
{ 
    //this is not necessary, but would be here 
} 

. 당신을 제외하고 뭔가를 원한다면, 당신은 할 수 있습니다 : 귀하의 경우

catch (Exception e) 
{ 
    //do something with e 
} 

를, 그것은과 같습니다

private static void Create(string name, string email) 
    { 
     try 
     { 
      using (SqlConnection conn = new SqlConnection(conn_string)) 
      { 
       SqlCommand cmd = conn.CreateCommand(); 

       cmd.CommandText = @"INSERT INTO dbo.Person (name, email) 
            VALUES (@name, @email)"; 
       cmd.Parameters.AddWithValue("@name", name); 
       cmd.Parameters.AddWithValue("@email", email); 
       conn.Open(); 
       cmd.ExecuteNonQuery(); 
       conn.Close(); 
      } 
     } 
     catch 
     { 
      //print custom error message 
     } 
    } 
+0

그래서 예외를 인스턴스화하는 것은 선택 사항입니다. 아주 좋은 덕분에, 나는 그것이 쉬워야한다는 것을 알았다. – user462238

+0

@ user462238 예외를 인스턴스화한다는 것은 무엇을 의미합니까? 코드에서 예외를 throw하면 예외 처리를 작성하는 방법에 관계없이 인스턴스가 만들어집니다. –

+0

@BrianRasmussen 예외를 Exception을 인수로 호출 할 코드가 없으면 해당 코드가 실행되지 않는다고 말합니다. catch 문 안에 웹 페이지 나 리디렉션을 넣을 수 있습니다. 그러면 리소스 사용량이 줄어 듭니다. 디버그 모드에서는 특정 예외를 잡아 메시지를 표시 할 수 있지만 프로덕션에서는 그렇지 않아도 ... 오류를 꽤 보이게 할 수 있습니다. – user462238