5/24/12

Viết chương trình tính số nhiên liệu tiêu thụ trung bình(sử dụng bẫy lỗi)

Mục đích:
Sử dụng lớp Exception đề bẩy lỗi chương trình.
Sử dụng MessageBox để hiển thị thông báo lỗi
Yêu cầu:
Viết chương trình tính số nhiên liệu tiêu thụ trung bình theo giao diện sau
Phải bắt lỗi chặc chẽ các trường hợp sau:
- Số dặm đường, số gallon tiêu thụ là số dương.
- Lỗi tràn số
- Lỗi chia cho số 0
- …




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Bai01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int miles, galon;
private void btnCalculate_Click(object sender, EventArgs e)
{
miles = int.Parse(txtMilesDriven.Text);
galon = int.Parse(txtGallonsOfGasUsed.Text);
lblEfficiency.Text = ((float)miles / galon).ToString();
}
private void txtMilesDriven_Validating(object sender, CancelEventArgs e)
{
//kiem tra nhap du lieu vao textbox
TextBox txt = (TextBox)sender;
try
{
//1. neu textbox rỗng
if (txt.Text == "")
{
//thong bao chua nhap du lieu
errorProvider1.SetError(txt, "chua nhap du lieu");
//giu con tro
e.Cancel = true;
}
else//2. da nhap du lieu
{
try
{
//2.2 tao bien tam x va kiem tra
int x = int.Parse(txt.Text);
//3. so nho hon 0
if (x < 0)
{
throw new ArithmeticException();
}
else//4. du lieu nhap > 0
{
errorProvider1.SetError(txt, "");
}
}
//tràn số
catch (OverflowException)
{
errorProvider1.SetError(txt, "so lon wa");
e.Cancel = true;
}
}

}
//2.1 du lieu ko phai la số
catch (FormatException)
{
//2.1.1 thong bao
errorProvider1.SetError(txt, "nhap so nguyen");
//2.1.2 giu con tro
e.Cancel = true;
}
//3.1 bat su kien so nho hon 0
catch (ArithmeticException)
{
//3.1.1 thong bao
errorProvider1.SetError(txt, "so phai >0");
//3.1.2 giu con tro
e.Cancel = true;
}
//5. cac truong hop loi khac
catch (Exception ex)
{
errorProvider1.SetError(txt, ex.Message.ToString());
e.Cancel = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("thoat y/n?", "thong bao 22222", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}


Bookmark and Share

0 comments:

Post a Comment

Next previous home

Cộng đồng yêu thiết kế Việt Nam Thiet ke website, danang