我正在尝试找到处理异常的理想方法。我用谷歌搜索并读到我应该将 try
catch
放在 catch
block 中来处理,但是如果嵌套 block 本身发生任何异常怎么办.
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");
}
在谷歌上我读到它应该装饰如下:
- 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"); }
If I do this way, then it will stuck in an infinite
try-catch
block.
我认为会有一些更好或正确的方法来处理这种情况。
最佳答案
I think there would be some better or the right way to handle this scenario.
这里没有任何陷阱,只是简单地说,首先不要让异常发生。
try...catch
是一种语言结构,可确保您处理边缘情况或错误,而这些情况或错误在一开始就没有进行缓解和设计,这就是为什么它是特殊代码的原因。
在您的代码中,您只是因为除以 0 而抛出错误,但在现实世界中,您想要处理该错误并提醒用户(或开发人员、服务器或其他任何人),然后处理实际的异常代码,例如:
static void PrintError()
{
Console.WriteLine("You must enter a valid number between {0} and {1}, excluding 0", int.MaxValue, int.MinValue);
}
static void Main(string[] args)
{
try {
int a = 10;
int b = 0;
PrintError(); // Tell user to enter valid numbers
while (b == 0) {
string user_input = Console.ReadLine();
if (int.TryParse(user_input, out b)) { // is it an actual number?
if (b == 0) { // no 0's remember user!??
PrintError();
} else {
// ok, everything checks out, so do what the system can actually handle without throwing an error
Console.WriteLine("a/b = {0}", (a / b));
}
} else {
PrintError();
}
}
} catch (Exception ex) {
Console.WriteLine("Something exceptional happened: {0}", ex);
}
}
这个例子可以进一步简化,但它表明除了一些实际异常的事情(即内存不足错误或其他一些系统错误)之外,没有可能实际发生的异常。
在具有多个类的较大代码库的情况下,异常处理程序和终结器将是您可以清理在代码的其他区域获取的资源的地方,例如关闭套接字或文件句柄以确保数据不丢失。
如果异常处理程序发生错误(可能发生并且确实发生的事情),您需要意识到这一点并知道在这种情况下可能会发生什么。
在 C# 应用程序使用 .NET 框架的情况下,在异常中抛出的异常只会导致应用程序崩溃并显示内部异常堆栈跟踪(相对于可能与实际异常更相关的“外部”异常) 如果没有处理。
有很多处理异常的“错误”方法(比如根本不处理它们),但考虑到异常的可变性,并没有真正“正确”的方法。
希望对您有所帮助。
关于c# - 如何处理 catch block 中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40647699/