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