7

In an Interview,Interviewer asked to me.. that I have a code which written in side the try and catch block like

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
 }

suppose we got an error on code line 3 then this will not go in the catch block but If I got error on any other line except line 3 it go in catch block

is this possible that if error occur on a particular line then it is not go in the catch block?

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
Vijjendra
  • 24,223
  • 12
  • 60
  • 92
  • 2
    Unplug the power chord from your computer at the moment line 3 is executed :) – Jan Apr 20 '11 at 20:56
  • The OOM and SO exceptions are hard (impossible?) to catch. – H H Apr 20 '11 at 21:00
  • What was the actual interview question? How to make it so line 3 doesn't cause the catch block to be entered, or given that code, what possible thing could line 3 be doing that would prevent the catch from catching anything? – David Yaw Apr 20 '11 at 21:11
  • @David: Question was "How to make it so line 3 doesn't cause the catch block to be entered" – Vijjendra Apr 20 '11 at 21:17
  • Do you get an Error or an Exception at line 3? – H H Apr 20 '11 at 21:21

3 Answers3

3

You could wrap line 3 in another try/catch block:

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;
}

Also the interviewer must have defined error. Was talking about an exception as an error could mean many things => crappy code, exception, not behaving as expected code, ...

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I deleted my answer. `ThreadAbortException` can be caught but it is raised again at the end of the catch block. – Aliostad Apr 20 '11 at 20:57
  • Any reason for the downvote? Please leave a comment when downvoting. – Darin Dimitrov Apr 20 '11 at 21:00
  • 1
    I didn't down vote, so no confusion here. but I wanted to comment on your ans anyway. Your ans still does not clarify why it didn't catch the exception. your solution sitll won't work if it is catch() with parameter. – Priyank Apr 20 '11 at 21:05
3

If you line 3 causes non CLS-compliant exceptions, it won't be catch'ed with parameterized catch() block. To catch all type of exceptions, use parameterless catch block.

try
{
// Statement which causes an exception
}

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

.net Exception catch block

Community
  • 1
  • 1
Priyank
  • 10,503
  • 2
  • 27
  • 25
0

Short Answer: Yes

There are errors that a catch block will not get. I think out of memory error. Another way an Exception can skip a block is if the error thrown is not one of the ones you defined.

Nick
  • 3,217
  • 5
  • 30
  • 42