当我们有一个try块的多个catch时,首先执行哪个catch块?为什么?请仔细阅读下面的例子。并提前建议,谢谢。 [英] which catch block is executed first when we have multiple catch for a single try block? and why ? plz go through the below ex. and advise, thanks in advance.

查看:291
本文介绍了当我们有一个try块的多个catch时,首先执行哪个catch块?为什么?请仔细阅读下面的例子。并提前建议,谢谢。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

try
{
//some code is executing..
}
catch(SqlException sqlex)
{
Console.WriteLine("sqlexception is returned")
}
catch(FormatException fx)
{
Console.WriteLine("FormatException is returned")
}
catch(Exception ex)
{
Console.WriteLine("Mainexception is returned");
}
catch
{
Console.WriteLine("exception without any args is returned");
}





所以,

1.这可能是什么输出,以及为什么。?

2.首先执行哪个catch块以及为什么?

3.如果我在try块之后立即声明catch(Exception ex),那么它将会不编译并为其他catch块提供错误 - 前一个catch子句捕获所有异常 - 这个带有参数的catch块也是如此。事件充当主异常或主异常块...?如果是这样的话为什么......?

请提前通知并感谢您的帮助。



so,
1. what might be the output of this, and why.?
2. which catch block will be executed at first and why?
3. If i declare catch(Exception ex)-immediately after the try block then it will not compile and gives an error for other catch blocks -"a previous catch clause catches all the exceptions" - so does this catch block with argument System.Exception acts as a master exception or main exception block..? if so why..?
Please advise and thanks for the help in advance.

推荐答案

Microsoft Visual Studio文档非常清楚这个话题。



参见 try-catch(C#参考) [ ^ ]



The Microsoft Visual Studio documentation is pretty clear on this topic.

See try-catch (C# Reference)[^]

Quote:

当抛出异常时,公共语言运行库(CLR)会查找处理此异常的catch语句。如果当前正在执行的方法不包含这样的catch块,则CLR会查看调用当前方法的方法,依此类推调用堆栈。如果没有找到catch块,则CLR向用户显示未处理的异常消息并停止执行该程序。

When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.







Quote:

可以在同一个try-catch语句中使用多个特定的catch子句。在这种情况下,catch子句的顺序很重要,因为catch子句是按顺序检查的。在不太具体的例外之前捕获更具体的例外。如果您订购了catch块,编译器会产生错误,以便永远无法访问以后的块。

It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.


这篇关于当我们有一个try块的多个catch时,首先执行哪个catch块?为什么?请仔细阅读下面的例子。并提前建议,谢谢。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆