YOMEDIA
Lecture Windows programming: Chapter 5 - Châu Thị Bảo Hà
Chia sẻ: Kiếp Này Bình Yên
| Ngày:
| Loại File: PPTX
| Số trang:29
49
lượt xem
3
download
Download
Vui lòng tải xuống để xem tài liệu đầy đủ
Chapter 5 of lecture Windows programming introduce about debugging and error handling. In this chapter presents the contents: Introduction to the errors in program, debugging, error handling. Inviting you to refer.
AMBIENT/
Chủ đề:
Nội dung Text: Lecture Windows programming: Chapter 5 - Châu Thị Bảo Hà
- Debugging and Error Handling
Chapter 5
Ebook: Beginning Visual C# 2010, chapter 7
Reference: CSharp How to Program, part D
- Contents
Introduction
Debugging
Error handling
Slide 2
- Introduction
Errors in program: a program can have three types of
errors:
compile-time errors: The compiler will find syntax errors
and other basic problems
run-time errors: A problem can occur during program
execution, such as trying to divide by zero, which causes a
program to terminate abnormally
logical errors: A program may run, but produce incorrect
results, perhaps using an incorrect formula
1-3
- Debugging
Debugging is the process of finding and correcting
logic errors in applications
applications are executed in two ways: with debugging
enabled (F5) or without debugging enabled (Ctrl+F5)
Techniques
debugging in nonbreak mode
outputting debugging information: Console.WriteLine(),
Debug.WriteLine()
debugging in break mode
using Breakpoints
Some windows in Debug\Windows: Autos, Locals,
Watch
demo… Slide 4
- Error handling
An exception is an indication of a problem that occurs
during a program's execution
format error,
arithmetic overflow,
out-of range array subscripts,
division by zero,
invalid method parameters
running out of available memory,
…
Your program should be able to handle these
exceptional situations. This is called exception
handling
Slide 5
- Error handling (cont.)
int tu = Convert.ToInt32( txtNumerator.Text );
int mau = Convert.ToInt32( txtDenominator.Text );
int result = tu / mau;
lblOutput.Text = result.ToString();
Slide 6
- Exception handling: try…catch
try{
// code that may cause exception
}
catch ( ExceptionTypeA e ){
// statement to handle errors occurring
// in the associated try block
}
catch ( ExceptionTypeB e ){
// statement to handle errors occurring
// in the associated try block
}
Slide 7
- Exception handling: try…catch...finally
try{
// code that may cause exception
}
catch ( ExceptionTypeA e ){
// statement to handle errors occurring
// in the associated try block
}
catch ( ExceptionTypeB e ) { … }
finally{
// statements always excuted
}
Slide 8
- Exception types
Some common exception classes
Exception Class Cause
DivideByZeroException An attempt was made to divide by zero.
FormatException The format of an argument is wrong.
IndexOutOfRangeException An array index is out of bounds.
An attempt was made to cast to an invalid
InvalidCastExpression
class.
OutOfMemoryException Not enough memory to continue execution.
StackOverflowException A stack has overflown.
Slide 9
- Example: try…catch
private void divideButton_Click( object sender, System.EventArgs e ) {
try
{
lblOutput.Text = "";
int x = Convert.ToInt32( txtX.Text );
int y = Convert.ToInt32( txtY.Text );
int result = x / y;
lblOutput.Text = result.ToString();
}
catch ( FormatException ) {
MessageBox.Show( "You must enter two integers", "Invalid Number
Format",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
catch ( DivideByZeroException er ) {
MessageBox.Show( er.Message, "Attempted to Divide by Zero",
MessageBoxButtons.OK, MessageBoxIcon.Error ); Slide 10
- The throw statement
A throw statement explicitly generates an exception
in code
There are two ways you can use the throw statement
rethrow the exception in a catch block:
catch( Exception e )
{
// Add code to create an entry in event log
throw;
}
throw explicitly created exceptions:
string strMessage = “EndDate should be greater than the
StartDate”;
ArgumentOutOfRangeException exp =
Slide 11
new ArgumentOutOfRangeException( strMessage );
- Defining properties with throw statement [1]
What should you public class DiemMonHoc {
do if an invalid private string mMaSV;
value is used? private string mMaMon;
private int mDiem;
do nothing public int Diem
assign a default {
value to the field get { return mDiem; }
set {
continue as if
if (value >= 0 && value
- Defining properties with throw statement [2]
set This can be handled using
{ try ... catch ... finally
if (value >= 0 && value
- .NET Exception hierarchy
The FCL provides two categories of exceptions
ApplicationException : represents exceptions thrown by the
users program
SystemException : represents exceptions thrown by the
CLR
Exception
ApplicationException SystemException
Slide 14
- Programmerdefined Exception classes
Creating customized exception types
should derive from class ApplicationException
should end with “Exception”
should define three constructors
a default constructor
a constructor that receives a string argument
a constructor that takes a string argument and an Exception
argument
Slide 15
- Programmerdefined Exception classes: Example
[1]
- Programmerdefined Exception classes: Example
[2]
class NegativeNumberException : ApplicationException {
public NegativeNumberException() :
base( "Phai nhap vao so khong am" )
{
}
public NegativeNumberException( string message ) :
base( message )
{
}
public NegativeNumberException( string message, Exception
inner )
: base( message, inner )
{
- Programmerdefined Exception classes: Example
[3]
private void squareRootButton_Click( object sender, System.EventArgs e ) {
outputLabel.Text = "";
try
{
double input = Double.Parse(inputTextBox.Text);
if ( input < 0 )
throw new NegativeNumberException( “Không tính được căn bậc hai
âm." );
double result = Math.Sqrt(input);
outputLabel.Text = result.ToString();
}
// BẮT lỗi định dạng số không hợp lệ
catch ( FormatException error ) {
MessageBox.Show( error.Message, "Lỗi nhập liệu", MessageBoxButtons.OK,
MessageBoxIcon.Error );
}
// BẮT lỗi nhập số âm
catch ( NegativeNumberException error ) {
MessageBox.Show( error.Message, “Lỗi nhập liệu", MessageBoxButtons.OK,
MessageBoxIcon.Error );
}
}
- Validating user input
When getting data from the user, you must ensure that
the entered data is valid
You can use various techniques for validating data:
by using standard controls such as comboboxes, listboxes,
radiobuttons, checkboxes, numericupdown, trackbar,...
by enabling or disabling data fields, depending on the state
of other fields
by capturing the user’s keystrokes and analyze them for
validity (Keystroke-level validation)
by analyzing the contents of the data field as a whole and
warn the user of any incorrect values when the user
attempts to leave the field or close the window (Field-level
validation)
Slide 19
- Keystrokelevel validation
When pressing a key on a control, three events occur
in the following order:
KeyDown event
KeyPress event
KeyUp event
Slide 20
Thêm tài liệu vào bộ sưu tập có sẵn:
Báo xấu
LAVA
ERROR:connection to 10.20.1.98:9315 failed (errno=111, msg=Connection refused)
ERROR:connection to 10.20.1.98:9315 failed (errno=111, msg=Connection refused)
Đang xử lý...