Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order catch blocks when try to handle an exception

try
{
    // throws IOException
}
catch(Exception e)
{
}
catch(IOException e)
{
}

when try block throws IOException, it will call the first catch block, not the second one. Can anyone explain this? Why does it call the first catch block?

like image 486
user Avatar asked Mar 25 '13 07:03

user


2 Answers

From try-catch (C# Reference);

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.

You should use

try
{
    // throws IOException
}
catch(IOException e)
{
}
catch(Exception e)
{
}

Be aware, Exception class is the base class for all exceptions.

like image 110
Soner Gönül Avatar answered Nov 03 '22 02:11

Soner Gönül


Exception class is the base class of all exceptions. So whenever exception is of any type is thrown it will first will be caught by the first catch block which can catch any type of Exception.

So try using IOCException before the Exception

You can see the hierarchy of IOCException here

like image 43
Anil Purswani Avatar answered Nov 03 '22 03:11

Anil Purswani