On catch catch块没有调用

时间:2011-04-20 20:51:03

标签: c#

在采访中,采访者问我...... 我有一个代码,它写在try和catch块中,如

try
 {
 //code line 1
 //code line 2
 //code line3 -- if  error occur on this line then did not go in the catch block
 //code line 4
 //code line 5
 }
 catch()
 {
  throw
 }

假设我们在代码行3上遇到错误 然后这不会进入catch区块 但如果我在除第3行之外的任何其他行上出错,则进入catch块

这可能是因为如果特定行发生错误,那么它不会进入catch块吗?

3 个答案:

答案 0 :(得分:3)

您可以将第3行换行到另一个try/catch块中:

try
{
    //code line 1
    //code line 2
    try
    {
        //code line3 -- if  error occur on this line then did not go in the catch block
    }
    catch { }
    //code line 4
    //code line 5
}
catch()
{
    throw;
}

面试官也必须定义错误。正在讨论异常,因为错误可能意味着很多事情=>糟糕的代码,异常,表现不像预期的代码,......

答案 1 :(得分:3)

如果第3行导致non CLS-compliant exceptions,则不会使用参数化的catch()块进行捕获。要捕获所有类型的异常,请使用无参数的catch块。

try
{
// Statement which causes an exception
}

catch //No parameters
{
//Handles any type of exception
}

.net Exception catch block

答案 2 :(得分:0)

简答:是的

catch块无法获得错误。我认为内存不足错误。异常可以跳过块的另一种方法是抛出的错误不是您定义的错误之一。