Exception Handling in C#
Submitted by donbermoy on Tuesday, July 15, 2014 - 20:20.
Sometimes, we encounter different errors along the program whenever we executed it. For example, the file does not exist in the given path, network connections are not connected, or any errors that you have experienced when you're learning how to program. This is what we've called Runtime Errors. One way to prevent it is the Structured exception handling.
In this tutorial for C#, we will used the Try-Catch-Finally statement. This control structure tests a piece of code, filters exceptions created by the execution of that code, and reacts differently based on the type of thrown exception.
Now lets start this tutorial! :)
1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application.
2. Next, add a Button named Button1 labeled as Compute, and lastly add two textboxes named TextBox1 and TextBox2. You must design your interface like this:
3. In your code module, code this for your Button1_Click:
We have now created our Try-Catch-Finally statement. In the try block, we code for it if there is no error when we run the program. We have initialized num1 and num2 as integer to hold the value of textbox1 and textbox2 respectively. Then we initialized result as integer to get the quotient of our num1 and num2. Then after it, it will exit from the Try Block. Next, in the Catch Block if the exception occurred or have an error, this catch block code will execute and will prompt the user "Cannot be divided by 0.". The code in the finally block will execute even if there is no Exceptions. That means if you write a finally block , the code should execute after the execution of try block or catch block.
- public void Button1_Click(System.Object sender, System.EventArgs e)
- {
- try
- {
- int num1;
- int num2;
- int result = 0;
- num1 = Convert.ToInt32(TextBox1.Text);
- num2 = Convert.ToInt32(TextBox2.Text);
- result = (int) (num1 / num2);
- MessageBox.Show("The answer is " + result.ToString());
- }
- catch (Exception)
- {
- MessageBox.Show("Cannot be divided by 0.");
- }
- finally
- {
- MessageBox.Show("Thank you for using this application");
- }
- }
Output:
The try blockOutput:
The catch blockOutput:
The finally block For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISwareAdd new comment
- 61 views