[英]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.