[英]Confused about throwing Exceptions in C#
我使用try/catch
和throw
來處理異常。 所以我正在使用try/catch
捕獲錯誤,其中包括諸如文件不可用等問題,然后在text
包含錯誤值時使用throw
。
我的Main()
的基本布局如下:
while ((line = sr.ReadLine()) != null)
{
try
{
//get the input from readLine and saving it
if (!valuesAreValid)
{
//this doesnt make the code stop running
throw new Exception("This value is not wrong");
} else{
//write to file
}
}
catch (IndexOutOfRangeException)
{
//trying to throw the exception here but the code stops
}
catch (Exception e)
{
//trying to throw the exception here but the code stops
}
因此,如果您注意到我在 try/catch
中引發了Exception
,但並沒有停止程序,而當嘗試在catch語句中引發Exception
,代碼停止了。 有誰知道如何解決這個問題?
如果你拋出一個內部異常catch
,它不會被通過處理catch
。 如果沒有catch
進一步上漲,你會得到一個未處理的異常。
try {
try {
throw new Exception("example");
} catch {
throw new Exception("caught example, threw new exception");
}
} catch {
throw new Exception("caught second exception, throwing third!");
// the above exception is unhandled, because there's no more catch statements
}
默認情況下,除非您在catch塊中重新拋出異常,否則該異常將停止在被捕獲的“ catch”塊中向上傳播。 這意味着程序將不會退出。
如果您不想捕獲異常,並且希望程序退出,則有兩個選擇:-刪除'Exception'的catch塊-將異常重新放入其catch塊中。
catch (Exception e)
{
throw e; // rethrow the exception, else it will stop propogating at this point
}
通常,除非您對異常有某種邏輯上的響應,否則請不要完全捕獲它。 這樣,您將不會“隱藏”或抑制應該導致程序錯誤輸出的錯誤。
另外,MSDN文檔也是了解異常處理的好地方: http : //msdn.microsoft.com/zh-cn/library/vstudio/ms229005%28v=vs.100%29.aspx
while ((line = sr.ReadLine()) != null)
{
try
{
//get the input from readLine and saving it
if (!valuesAreValid)
{
//this doesnt make the code stop running
throw new Exception("This value is not wrong");
} else{
//write to file
}
}
catch (IndexOutOfRangeException)
{
//trying to throw the exception here but the code stops
}
catch (Exception e)
{
//trying to throw the exception here but the code stops
throw e;
}
我不確定“停止程序”是什么意思。 如果您不處理異常,則程序將停止,但是您的代碼正在處理通過catch(Exception e)塊引發的異常。 或者,也許您的意思是您想退出while循環,在這種情況下,您可以使用break 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.