我在Class中数据库连接失败时发生异常。问题是如何通知我的主窗口捕获此异常并显示一个消息框以通知我的用户?
由于
答案 0 :(得分:1)
使用像这样的Try ... Catch子句:
try
{
// The code that could generate an exception
}
catch(Exception ex)
{
MessageBox.Show("Error: " ex.Message);
}
或者,如果您使用的是SQL-Server连接,请按以下方式使用:
try
{
// The code that could generate an exception
}
catch(SqlException ex)
{
MessageBox.Show("SQL Error: " ex.Message);
}
答案 1 :(得分:0)
感谢。我可能没有清楚地提出我的问题。我的意思是这个例外 发生在一个类中,但是消息框应该显示在一个类中 其他windows类。那么如何沟通并显示此错误?
根据你在其中一条评论中的澄清:
因此,如果您的课程TestClass.cs
中包含方法测试。
public void Test()
{
//if you want to throw an exception defined by your business logic
if(someCondition == false)
throw CustomException();
//if you have exception in the code
int a = 5;
int b =0;
//here you will be thrown an exception can't divide by 0.
int c = a/b;
}
您的winform按钮单击或其他
public void Button_Click1(object sender, EventArgs e)
{
try
{
TestClass cl = new TestClass();
cl.Test();
}
catch(CustomException custEx)
{
//this for your Bussines logic exception
//write your message
}
catch(DivideByZeroException div)
{
//this for divide by zero exception
//write message
}
//you can catch all other exception like this but I don't advice you to do that
catch(Exception ex)
{
//for this to working properly, this catch should be under all of others(last priority)
}
}