Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution of multiple catch blocks [duplicate]

Tags:

c#

Possible Duplicate:
executing multiple catch blocks

Can multiple catch blocks be executed for a single try statement?How can we handle the catch blocks?Can we create try without catch block??

like image 589
chandra sekhar Avatar asked Sep 25 '12 12:09

chandra sekhar


1 Answers

There can be multiple catch blocks (as said in other answers already), but only the one that first matches the exception type is executed. That means you need to order the catch blocks properly. For example:

try
{
}
catch (Exception exp1)
{
    // Block 1
}
catch (IOException exp2)
{
    // Block 2
}

Block 2 will never be executed, as block 1 catches every exception (all exception classes are derived from Exception).

try
{
}
catch (IOException exp1)
{
    // Block 1
}

catch (Exception exp2)
{
    // Block 2
}

In this example, block 2 will only be executed if the exception is not an IOException or derived from IOException. If an IOException is thrown, only block 1 will execute, block 2 will not.

like image 142
Thorsten Dittmar Avatar answered Oct 23 '22 09:10

Thorsten Dittmar