user462238
user462238

Reputation: 43

Error and Exception Handling

I have a simple crud application, and i want to handle the errors gracefully as they say.

I am just not getting try and catch. I started learning some python before I went to school for C# and it doesn't really work the same. Here's my code,

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 name=@name, email=@email
                                    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 id=@id";
                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 :(");
            }
        }
    }
}

It works, but it's fragile. This is a console app that I will one day turn into an html solution, but...

I'm not sure where to put the try catch block, and I have no idea where to put the exception. Then I'm on msdn and they tell me they use a finally. Finally, something I can understand. So, coming from python i would say the try is obviously the same, the catch (){} in c sharp is like except: in python but I haven't used an argument for the except in python. I'm such a noob. I think I can use the Exception object in .NET but I don't need it. I just want to write a custom message if any error occurs... I mean, how hard is it to write a href? I just can't get it to work properly.

So my question is, how would I structure for example the Create method, considering I would like to to keep the try catch block inside each crud operation?

Upvotes: 0

Views: 365

Answers (1)

dursk
dursk

Reputation: 4445

Basic C# exception handling:

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

The catch block will catch all exceptions in the above example. If you want to do something with the exception, you can do:

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

In your case, it would look like:

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
        }
    }

Upvotes: 3

Related Questions