我想获得处理异常的理想方法。我搜索了&,我应该把try
catch
放在catch
块中,以便处理,但是如果在嵌套块本身发生了什么异常。如何处理catch块中的异常?
try
{
int a = 10;
int b = 0;
int c = a/b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
int a = 10; int b = 0;
int c = a/b;
Console.WriteLine(ex.Message.ToString());
Console.ReadKey();
}
finally
{
Console.WriteLine("Some Exception");
}
在google搜索,我读了它应该如下布置:
- If exception occurs in Catch block itself then how to handle it in C#?
- If exception occurs in Catch block itself then how to handle it in C#?
-
try { int a = 10; int b = 0; int c = a/b; Console.WriteLine(c); Console.ReadKey(); } catch (Exception ex) { try { } catch(Exception innerEx) { // What if exception here also occurs. } } finally { Console.WriteLine("Some Exception"); }
如果我这样做,那么它会卡在一个无限的
try-catch
块。
我认为会有一些更好或正确的方式来处理这种情况。
在某些情况下,如果您的代码处于您的异常处理中发生异常的状态,您应该会发生崩溃。如果应用程序崩溃并不好,您需要考虑您的代码如何“纾困”,或中止造成问题的流程。 –
我会与上面的评论。从我的视角来看,这是一个设计问题,而不是语言问题。我也可以用'if'语句构建上面的例子 - >如果出错了,我执行失败处理 - >如果失败处理出错,我执行失败处理,如果.... – Moerwald
重要的是你学会了很很快发现异常处理是**糟糕的** _unless_您有一个特定的异常,您可以捕捉并且可以正确处理。如果你曾经写过'catch(Exception ...)',那么你可能会让你的生活变得更加艰难 - 不容易。 – Enigmativity