Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of Catch blocks important?

Tags:

c#

exception

Just making sure I understand it well. Is the correct schema correct? Catching the most specific exceptions first to catching broader exceptions with general catch at the end of the set of catch blocks.

try
{
 some code
}


catch(SomeSpecificException ex)
{
}
catch(LessSpecificException ex)
{
}
catch
{
  //some general exception
}
like image 613
Loj Avatar asked Jan 06 '11 12:01

Loj


People also ask

Does order of catch block matter?

The order of catch blocks does matter It's because if we handle the most general exceptions first, the more specific exceptions will be omitted, which is not good, as Java encourages handling exceptions as much specific as possible.

How should catch blocks be arranged?

How should you arrange Catch blocks? Only one Catch block for each Try code block, located after the Try code block but before the End Try statement. Several Catch blocks within one Try code block, arranged starting with Exception and ending with the most specific exception.

Does the order of catch blocks matter in C++?

@Joe Order of catch blocks does not matter, if your exception classes are not related to each other. However, in your code you are catching exception , and also some classes that are inherited from exception (see tutorialspoint.com/cplusplus/cpp_inheritance.htm ).

Which order should we catch the exceptions?

Order of exceptions If you have multiple catch blocks for a single try and if the exceptions classes of them belong to the same hierarchy, You need to make sure that the catch block that catches the exception class of higher-level is at last at the last in the order of catch blocks.


1 Answers

I believe it won't let you write it in the incorrect order.

This generates an error:

try
{
    throw new OutOfMemoryException();
}
catch(Exception ex)
{
    "B".Dump();
}
catch(OutOfMemoryException ex)
{
    "A".Dump();
}
like image 163
Rob Avatar answered Oct 19 '22 06:10

Rob