[英]Prevent console app from closing after catching exception
我已经使用SmartIrc4Net用C#编写了一个IRC机器人,该机器人的目的是在识别命令时仅提供信息。
我的问题是,代码中可能会发生异常,导致应用程序关闭,但是有可能保持应用程序运行,并且没有任何“按任意键继续”消息出现。 理想情况下,这应该只记录异常并继续。
我知道我可以首先处理异常,但是在每个命令的基础上验证所有输入将花费很长时间。 甚至可能还有我可能没有提到的其他例外情况。
static void Main(string[] args)
{
IrcClient bot = new IrcClient();
// attach events
try
{
// connect to server, login etc
// here we tell the IRC API to go into a receive mode, all events
// will be triggered by _this_ thread (main thread in this case)
// Listen() blocks by default, you can also use ListenOnce() if you
// need that does one IRC operation and then returns, so you need then
// an own loop
bot.Listen();
// disconnect when Listen() returns our IRC session is over
bot.Disconnect();
}
catch (ConnectionException e)
{
Console.WriteLine("Couldn't connect! Reason: " + e.Message);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(">> Error: " + e);
}
}
将程序包装在while(true)
块中。
static void Main(string[] args)
{
while(true){
IrcClient bot = new IrcClient();
// attach events
try
{
// connect to server, login etc
// here we tell the IRC API to go into a receive mode, all events
// will be triggered by _this_ thread (main thread in this case)
// Listen() blocks by default, you can also use ListenOnce() if you
// need that does one IRC operation and then returns, so you need then
// an own loop
bot.Listen();
// disconnect when Listen() returns our IRC session is over
bot.Disconnect();
}
catch (ConnectionException e)
{
Console.WriteLine("Couldn't connect! Reason: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine(">> Error: " + e);
}
}
}
代码中可能会发生异常,导致应用程序关闭,但有可能使应用程序保持运行状态,并且没有任何“按任意键继续”消息出现。
好吧,是的,您可以以这种方式编写应用程序,但是我可以保证这不是您认为的简单方法。 抛出异常时, 出现了问题 。 您不会通过耸耸肩膀并继续前进来神奇地修复任何东西,这可能会导致更多的事情出错。
想象一下,您有打开文件的代码,然后对该文件的内容进行处理,然后向用户显示一些结果。 如果文件不存在,将引发异常。 如果您只是捕获异常,则什么也不做,然后继续执行“对文件的内容执行某些操作”代码...恭喜,现在您可以处理更多的异常,因为文件中没有内容 。 您再次耸了耸肩,继续执行“显示结果”代码...恭喜,还有更多例外,因为没有结果!
没有懒惰的出路。 捕获特定的异常,并适当地处理它们。 是的,这需要更多的精力。 是的,它需要更多代码。 是的,您将不得不考虑每种情况下“适当处理”的含义。 那是编程。
你应该试试这个
static void Main(string[] args)
{
bool shouldStop=false;
while(!shouldStop){
IrcClient bot = new IrcClient();
shouldStop=true;
// attach events
try
{
// connect to server, login etc
// here we tell the IRC API to go into a receive mode, all events
// will be triggered by _this_ thread (main thread in this case)
// Listen() blocks by default, you can also use ListenOnce() if you
// need that does one IRC operation and then returns, so you need then
// an own loop
bot.Listen();
// disconnect when Listen() returns our IRC session is over
bot.Disconnect();
}
catch (ConnectionException e)
{
Console.WriteLine("Couldn't connect! Reason: " + e.Message);
shouldStop=false;
}
catch (Exception e)
{
Console.WriteLine(">> Error: " + e);
shouldStop=false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.