Short answer:
It will display the value 11. The value 21 would never be displayed as the catch block is executed only when there is an exception.
Long answer
Come on, straight from MSDN
When an Exception is thrown, the common language Runtime (CLR) looks
for the catch statement that Handles this Exception. If the Currently
executing method does not contain such a catch block, the CLR looks at
the method that called the Current method, and so on up the call
stack. If no catch block is found, then the CLR displays an unhandled
Exception message to the user and stops Execution of the program.
That is, when an exception is raised, the CLR searches for the closest catch to where this exception was raised and executes its code block. This means that if the current code block where the exception was raised does not have a catch
, this catch
will be searched in the methods that called it up to reach the top of the call stack, where will be raised an exception of type Unhandled Exception
for the user, stopping the execution of the program.
So...
The rest of the existing code within a Try runs after
find an Exception or skip directly to the code within the
(Catch exception and)
The block try
contains the code that can raise an exception, and it will run as long as there is no exception or until it is finalised. In other words, if an exception occurs, it will search directly for the nearest catch without executing the rest of the code within the block try
.
The Try block contains the guarded code that may cause the Exception.
The block is executed until an Exception is thrown or it is completed
successfully. For example, the following Attempt to cast a null Object
raises the Nullreferenceexception Exception:
Why this behavior?
An exception indicates that something unusual occurred during the execution of your code. If "something wrong" occurred during this run, do you want the rest of your code to run normally? The block catch
should be used precisely to execute a specific code for these abnormal cases, when you you know they can happen.
The catch block can be used in various ways, as can be seen below:
catch(InvalidOperationException ex)
{
//Deve ser executado quando uma exceção do tipo InvalidOperationException seja levantada
}
catch(SqlException ex) when (ex.Message.Contains("TIMEOUT"))
{
//Deve capturar uma exceção do tipo SqlException e que contenha no message a palavra TIMEOUT
}
catch(Exception ex)
{
//Deve capturar uma exceção que não seja uma InvalidOperationException ou **SqlException que não contenha** no message a palavra TIMEOUT
}
Avoid capturing generic exceptions (Exception ex)
in specific codes of your application, unless you know what you are doing (logging at the highest point of the system, for example), or raise it again with a throw
or by placing it as a Inner Exception
. Finally, there are some categories of exceptions that you can use to guide yourself about your treatment:
- Usage errors: A usage error represents an error in program logic
which may result in an exception. However, this type of error should not
be solved with a block
try catch
, and yes with a modification in the
code to be executed. It is an error that you know it’s gonna happen and
that can be avoided.
- Program error: A runtime error that cannot be avoided in building the code can fall into this category. Imagine that you need to read a file in a specific directory. Not to fall into Usage error, you check before if this file exists so you can then use it. However, although the check has returned true to the file’s existence, at the time of reading it found itself unavailable (has been deleted or is being used by another process), raising an exception of
FileNotFoundException
, or similar.
- System failures: System failures are exceptions that can occur at runtime and that normally cannot be handled very usefully. What you as a developer can do if a
OutOfMemoryException
? You can however, log the information of this exception in a log before the application is finalized, for further analysis in order to prevent this error from occurring again.
Recommended readings
If the
Exception
occur on the line you are commenting the result would be11
, for thex
would leave the block with value10
.– Fernando Leal
I agree with Fernando, the value of X will be printed as 11.
– rodrigorf