Mất 1 phút đọc

Xử lý biệt lệ trong C#

Nội dung

  • Tại sao phải xử lý biệt lệ
  • Các cấp độ lỗi thường gặp: biên dịch, runtime, logic
  • checked error, unchecked error

Tại sao phải xử lý biệt lệ?

  • Trong quá trình thực thi phần mềm sẽ có những lỗi phát sinh mà trong quá trình coding ta đã dự đoán hoặc chưa dự đoán được
  • Có những lỗi được phát sinh do Application Exception hoặc do SystemException
  • Việc kiểm soát các biệt lệ giúp cho phần mềm tiếp tục hoạt động nếu lỗi xảy ra hoặc cũng đưa ra các gợi ý bên phía User Problem

Các cấp độ lỗi thường gặp

  • Lỗi biên dịch
  • Lỗi runtime exception
  • Lỗi logic exception – sai nghiệp vụ yêu cầu

Checked error, unchecked error

Unchecked error

try Block

try
{
//Code that may cause Exception
}

catch Block

try
{//code that may cause exception
}
catch (ArithmeticException ex1)
{//Process Exception here
}
catch (EvaluateException ex2)
{//Process Exception here
}

The throw statement

if (n < 0)
{
ArithmeticException ex1 =
new ArithmeticException(“n
must greater than Zero”);
throw ex1;
}

finally Block

The finally block contains code that always executes, whether or not any exception occurs.

try
{//code here
}
finally
{//do something
}

Define New Exception

class CMyException : ApplicationException
{
private Exception innerException;
private string m_strMsg;
public string CustomMessage
{get { return this.m_strMsg; }
set { this.m_strMsg = value; }
}
public CMyException(){ }
public CMyException(string strMsg,Exception ex)
{ this.m_strMsg = strMsg;
this.innerException = ex;
}
}

Define New Exception
try
{ int t = 0,n=5;
n = n / t;
}
catch (Exception ex)
{
CMyException myEx=new CMyException
(“Lỗi rồi”, ex.InnerException); MessageBox.Show(myEx.CustomMessage);
}

Error provider

private bool validateName(){
bool bValid = true;
txtTen.Text.Trim();
if (txtTen.Text == “”){
bValid = false;
errorProvider1.SetError(txtTen, “Tên không được để trống”);
}
else{ errorProvider1.SetError(txtTen, “”);
}
return bValid;
}

5/5 - (2 Bình chọn)
452 lượt xem

11/03/2022 Ứng Dụng Miễn Phí

Bài viết liên quan

Block "5_tab_footer" not found