Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Error catch block did not call

Tags:

c#

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?

like image 481
Vijjendra Avatar asked Apr 20 '11 20:04

Vijjendra


People also ask

What happens when a catch block is not given?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.

How do you handle errors in catch block?

You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.

Can we use error in catch block?

You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.

What is the type of error in catch block?

catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”.


2 Answers

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, ...

like image 168
Darin Dimitrov Avatar answered Nov 17 '22 01:11

Darin Dimitrov


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

like image 44
Priyank Avatar answered Nov 17 '22 02:11

Priyank