Just to add up to the existing solution provided...
Quote:
Which catch block is executed first when we have multiple catch for a single try block?
Depending on the type of exception your application code generates. Since you were catching a few
Exception
types then:
(a) When your SQL Server throws a warning or error then the
SqlException
catch block get's executed.
(b) When you are trying to convert something that is not well formed, or the format of an argument is invalid then the
FormatException
catch block gets executed.
(c) When a null reference or invalid operation occurred then it will goes to the
Exception
catch block since you didn't specifically handle
NullReferenceException
and
InvalidOperationException
. The
Exception
type is typically used to handle generic exceptions.
Quote:
and why ?
Multiple
Catch
block are typically used to handle different kinds of
Exception
. Just like in your example:
SqlException
,
FormatException
and
Exception
types (keep in mind that there are many types of Exceptions depending on what operation you are trying to do).
Exceptions are a type of error that occurs during the execution of an application.
Errors
are typically problems that happens unexpctedly. Whereas,
Exceptions
are expected to happen within application code that's why it is important to handle expected exceptions and catch them specifically to easily identify which of which causes the exception to happen. Handling specific exceptions is very useful when doing some logging and allows an application to transfer control from one part of the code to another.