如何将一个异常从一个类返回到调用它的形式 [英] how to throw an exception from a class back to the form that called it
本文介绍了如何将一个异常从一个类返回到调用它的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void childDirectoryToolStripMenuItem_Click(object sender,EventArgs e)
{
try
{
SQL.createTable(childDirectory); //这个线
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format(发生错误:{0},ecp.Message)) ;
}
}
并有一个名为SQL的类。 C#类不能向用户发出一个messageBox,只有Console.WriteLine:
static public void createTable(string tableToCreate)
{
try
{
。
。
。
。
}
catch(SqlException exp)
{
Console.WriteLine(Database not created:+ exp.Message,Error);
}
}
如何将这个SqlExecption抛回Form中。 cs电话?对不起,如果我的措辞是错误的,希望你能明白我在做什么。
解决方案
static public void createTable(string tableToCreate)
{
try
{
。
。
。
。
}
catch(SqlException exp)
{
Console.WriteLine(Database not created:+ exp.Message,Error);
throw exp;
}
}
并抓住它:
private void childDirectoryToolStripMenuItem_Click(object sender,EventArgs e)
{
try
{
SQL.createTable ( childDirectory); //这个线
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format(发生错误:{0},ecp.Message)) ;
}
catch(SqlException exp)
{
}
}
但是除非有必要,否则在调用方法中捕获它时,不需要在调用方法中捕获异常。
Hello I have a regular WinForm that calls this:
private void childDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
SQL.createTable("childDirectory"); //THIS LINE
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format("An error occurred: {0}", ecp.Message));
}
}
and have a class named "SQL". The C# class cannot throw a messageBox to the user, only Console.WriteLine:
static public void createTable(string tableToCreate)
{
try
{
.
.
.
.
}
catch (SqlException exp)
{
Console.WriteLine("Database not created: " + exp.Message, "Error");
}
}
How can I throw this SqlExecption back in the Form.cs call? Sorry if my wording is wrong, hopefully you can understand what I'm trying to do.
解决方案
static public void createTable(string tableToCreate)
{
try
{
.
.
.
.
}
catch (SqlException exp)
{
Console.WriteLine("Database not created: " + exp.Message, "Error");
throw exp;
}
}
And catch it with:
private void childDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
SQL.createTable("childDirectory"); //THIS LINE
}
catch(SystemException ecp)
{
MessageBox.Show(string.Format("An error occurred: {0}", ecp.Message));
}
catch (SqlException exp)
{
}
}
But unless it is necessary you don't need to catch exception in called method if you catch it in calling method.
这篇关于如何将一个异常从一个类返回到调用它的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文