16. Exception Handling Notes
16. Exception Handling Notes
Note: Most people are saying Runtime Errors Are Exceptions which is not true.
Exceptions are classes that are responsible for abnormal termination of the
program when runtime errors occur.
1. IndexOutOfRangeException
2. FormatException
3. NullReferenceException
4. DivideByZeroException
5. FileNotFoundException
6. SQLException,
7. OverFlowException, etc.
Each exception class provides a specific exception error message. All the
above exception classes are responsible for abnormal termination of the
program as well as they will be displaying an error message which specifies
the reason for abnormal termination i.e. they provide an error message
specific to that error.
Note: Exception class is the superclass of all Exception classes in C#.
Types of Errors
When we write and execute our code in the .NET framework then there is a
possibility of two types of error occurrences. They are as follows:
1. Compilation Errors
2. Runtime Errors
Compilation Error in C#
The errors which are occurred at the time of program execution are
called runtime errors. These errors occurred at runtime due to various
reasons such as when we are entering the wrong data into a variable,
trying to open a file for which there is no permission, trying to connect
to the database with the wrong user id and password, the wrong
implementation of logic, and missing required resources, etc. So, in
simple words, we can say that the errors which are come while running
the program are called runtime errors.
Runtime errors are dangerous because whenever they occur in the
program, the program terminates abnormally on the same line where
the error gets occurred without executing the next line of code.
Note: The compiler will never check the logic; the compiler will only check
the syntaxes. So, the compiler will identify the syntax error, but not the logical
error.
Is Runtime Errors Are Dangerous?
Yes, runtime errors are dangerous. See, if you are transferring the
money, then there are two updated statements. One update
statement will deduct the money from the source account and
another update statement add the money to the destination account.
Suppose, the first update statement was executed successfully and
before executing the second update statement, some runtime error
occurred because of some reason. That means the money is deducted
from your account but not added to the destination account.
Then what you will do? You might be contacted with the bank, you
might be going to the nearest bank and investigating what happens,
Why the money is deducted from my account, and why it is not added
to the destination account. This is the problem and this very dangerous
and this is because we are not handling the runtime errors in our
application.
The process of catching the exception for converting the CLR given
exception message to an end-user understandable message and for
stopping the abnormal termination of the program whenever runtime errors
are occurring is called Exception Handling in C#. Once we handle an
exception under a program we will be getting the following advantages
1. Logical Implementation
2. Try Catch Implementation
What is the Logical Implementation in C# to Handle Exception?
The try keyword establishes a block in which we need to write the exception
causing and its related statements. That means exception-causing
statements and the related statements which we should not execute when
an exception occurred must be placed in the try block. When the exception
occurred, the CLR will create an instance of the Exception class based on the
logical error and then throw that Exception object which is going to be
handled by the corresponding catch block.
Catch Block:
The catch block is used to catch the exception that is thrown from its
corresponding try block. It has the logic to take necessary actions on that
caught exception. The Catch block syntax in C# looks like a constructor. It
does not take accessibility modifiers, normal modifiers, or return types. It takes
only a single parameter of type Exception or any child class of the parent
Exception class. Inside the catch block, we can write any statement which is
legal in .NET including raising an exception. In this case, we can stop the
abnormal termination of the program and we can also give user
understandable error message so that the user can take necessary action to
resolve the error.
Finally Block:
The keyword finally establishes a block that definitely executes the statements
placed in it irrespective of whether any exception has occurred or not. That
means the statements that are placed in finally block are always going to be
executed irrespective of whether any exception is thrown or not, irrespective
of whether the thrown exception is handled by the catch block or not.
Syntax to use Exception Handling
1) If all the statements under the try block are executed successfully, from
the last statement of the try block, the control directly jumps to the first
statement that is present after the catch block (after all catch blocks)
without executing the catch block (it means there is no runtime error in
the code at all).
2) If any of the statements in the try block causes an error, from that
statement without executing any other statements in the try block, the
control directly jumps to the catch blocks which can handle that
exception.
3) If a proper catch block is found that handles the exception thrown by
the try block, then the abnormal termination stops there, executes the
code under the catch block, and from there again it jumps to the first
statement after all the catch blocks.
4) If a matching catch block is not found, then the generic catch block is
going to execute to handle the abnormal termination.
5) If you don’t have the generic catch block and if any of the catch
blocks are unable to handle the exception, then again, the program
execution terminates abnormally.
Source: This property will store the name of the application from which the
exception has been raised.
HelpLink: This is used to provide a link to any file /URL to give helpful
information to the user about why this exception is raised.
StackTrace: This is used to provide more information about the Exception like
the reason for the exception, at what method and what class the exception
occurred, and at what line number the exception has occurred which helps
us to resolve the issue.
It is possible in C#, to write multiple catch blocks for a given try block. When
we implement multiple catch blocks in C# for a given try block, then at any
given point of time only one catch block is going to be executed and other
catch blocks will be ignored.
When should we write Multiple Catch Blocks in C# for a Single Try block?
We need to write multiple catch blocks in C# for a single try block because
of the following reasons
The keyword finally establishes a block that definitely executes the statements
placed in it irrespective of whether any exception has occurred or not. That
means the statements that are placed in finally block are guaranteed to be
going to be executed irrespective of whether any exception is thrown or not
in the try block, irrespective of whether the thrown exception is handled by
the catch block or not. Following is the syntax to use finally block in C#,
a. Try, Catch, and Finally: In this case, the exception will be handled, and
stopping the abnormal termination along with the statements that are
placed within the “finally” block gets executed at any cost.
b. Try and Finally: In this case, abnormal termination will not stop when a
runtime error occurs because exceptions are not handled but even if
an abnormal termination occurs, the finally blocks get executed.
In how many ways we can use try-catch and finally block
We can use try-catch-finally in three different ways. They are as follows:
Try and Catch: In this case, the exception will be handled and stop the
abnormal termination.
Try, Catch, and Finally: In this case, the exception will be handled, and
stopping the abnormal termination along with the statements that are
placed within the “finally” block gets executed at any cost.
Try and Finally: In this case, abnormal will not stop when a runtime error
occurs because exceptions are not handled but even if an abnormal
termination occurs also finally blocks get executed.
Types of Exceptions
DivideByZeroException
IndexOutOfRangeException
FormatException
SQLException
NullReferenceException, Etc.
What are Application Exceptions
Now, to create a Custom Exception class in C#, we need to follow the below
steps.
Step1: Define a new class inheriting from the predefined Exception class so
that the new class also acts as an Exception class.
Step2: Then as per your requirement, override the virtual members that are
defined inside the Exception class like Message, Source, StackTrace, etc. with
the required error message.
What is Inner Exception