|
| 1 | +--- |
| 2 | +Title: Try Catch Statement |
| 3 | +--- |
| 4 | + |
| 5 | +## Try Catch in CSharp |
| 6 | +In the world of programming most of the time for the newbie, they only code in a linear way, assuming that it will be a good practice |
| 7 | +and most of the time learning to error exception handling is left behind. |
| 8 | + |
| 9 | +But it's only just a normal for newbie programmers as I came from the same shoes.:) |
| 10 | + |
| 11 | +Since I start developing I always thinking in linear way of coding until such time that my code is mixing up together. |
| 12 | + |
| 13 | +I really came accross to hardly maintain especially I don't have any error handlers before but now I always implement it in my bunch of |
| 14 | +code as necessary. |
| 15 | + |
| 16 | +In C# the try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different |
| 17 | +exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. |
| 18 | +If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, |
| 19 | +and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops |
| 20 | +execution of the program. |
| 21 | + |
| 22 | +You can read more from here in [MSDN](https://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.90).aspx). |
| 23 | + |
| 24 | +Going back! |
| 25 | + |
| 26 | +Here is my example of coding in C# for exception handling. |
| 27 | + |
| 28 | +``` |
| 29 | +protected void btnSave_Click(object sender, EventArgs e) |
| 30 | + { |
| 31 | + var insCmd = new MySqlCommand("INSERT INTO user VALUES (@Id, @firstNm, @lastNm, @Role)", con); |
| 32 | +
|
| 33 | + insCmd.Parameters.AddWithValue("@Id", txtId.Text); |
| 34 | + insCmd.Parameters.AddWithValue("@firstNm", txtFirstNm.Text); |
| 35 | + insCmd.Parameters.AddWithValue("@lastNm", txtLastNm.Text); |
| 36 | + insCmd.Parameters.AddWithValue("@Role", ddlRole.SelectedItem); |
| 37 | +
|
| 38 | + try |
| 39 | + { |
| 40 | + con.Open(); |
| 41 | + insCmd.ExecuteNonQuery(); |
| 42 | + lblMessage.Visible = true; |
| 43 | + lblMessage.Text = "Successfully Saved!"; |
| 44 | + |
| 45 | + } |
| 46 | + catch (Exception ex) |
| 47 | + { |
| 48 | + lblMessage.Visible = true; |
| 49 | + lblMessage.Text = "Error: " + ex.Message; |
| 50 | +
|
| 51 | + } |
| 52 | + con.Close(); |
| 53 | + txtFirstNm.Text = ""; |
| 54 | + txtLastNm.Text = ""; |
| 55 | + } |
| 56 | +``` |
| 57 | +The above code is came from one of my web based project where try catch is execute a message error if there will be an invalid character |
| 58 | +to insert in the database. |
| 59 | + |
| 60 | +Through this strategy it will avoid your program or web application to crushed in an unexpected situation. |
| 61 | + |
| 62 | +Hope it helps! |
0 commit comments