Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

16. Exception Handling Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

16. Exception Handling Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

 What is an Exception

An Exception is a class in C# which is responsible for abnormal termination of


the program when runtime errors occur while running the program. So, these
errors (runtime) are very dangerous because whenever the runtime errors
occur in the programs, the program gets terminated abnormally on the same
line where the error gets occurred without executing the next line of code.

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.

Who is Responsible for the Abnormal Termination of the Program Whenever


Runtime Errors occur?

Objects of Exception classes are responsible for abnormal termination of the


program whenever runtime errors occur. These exception classes are
predefined under BCL (Base Class Libraries) where a separate class is
provided for each and every different type of exception like

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 error that occurs in a program at the time of compilation is known


as a compilation error (compile-time error). These errors occur due to
syntactical mistakes in the program. That means these errors occur by
typing the wrong syntax like missing double quotes in a string value and
missing terminators in a statement, typing wrong spelling for keywords,
assigning wrong data to a variable, trying to create an object for
abstract class and interface, etc. So, whenever we compile the
program, the compiler recognizes these errors and it will show us the list
of errors.
 So, in simple words, we can say that this type of error occurs due to a
poor understanding of the programming language. These errors are
identified by the compiler and can be rectified before the execution of
the program only. So, these errors do not cause any harm to the
program execution.
Runtime 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.

What is Exception Handling

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

a. We can stop the Abnormal Termination


b. We can perform any corrective action that may resolve the problem.
c. Displaying a user-friendly error message, so that the user can resolve
the problem provided if it is under his control.
Why do we need Exception Handling in C#?
We need Exception Handling in C# because of the following two reasons.

a. To stop the Abnormal Termination of the program


b. To provide users with understandable messages when an exception is
raised. So that users can make a decision without the developer’s help.

Basically, by implementing Exception handling we are providing life to a


program to talk to the user on behalf of a developer.
What is the Procedure to Handle Exceptions in C#?
The Exception Handling in C# is a 4 steps procedure

a. Preparing the exception object that is appropriate to the current


logical mistake.
b. Throwing that exception to the appropriate exception handler.
c. Catching that exception
d. Taking necessary actions against that exception
How can we handle an Exception in .NET?
There are two methods to handle the exception in .NET

1. Logical Implementation
2. Try Catch Implementation
What is the Logical Implementation in C# to Handle Exception?

In logical Implementation, we need to handle the exception by using logical


statements. In real-time programming, the first and foremost importance is
always given to logical implementation only. If it is not possible to handle an
exception using logical implementation, then we need to go for try-catch
implementation.
Exception handling in C# using Try Catch implementation

To implement the try-catch implementation, the .NET framework provides


three keywords. They are as follows:
A. Try
B. Catch
C. finally
Try Block:

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.

Properties of Exception Class

Some of the important properties of the Exception Class are properties as


follows:
Message: This property will store the reason why an exception has occurred.

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.

Multiple Catch Blocks

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

1. To print messages specific to an exception or


2. To execute some logic specific to an exception

The 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 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

Before understanding how to create Custom Exceptions or used Defined


Exceptions in C#, let us first understand what are the different types of
Exceptions available. In C#, the exceptions are divided into two types. They
are as follows:

1) System Exception: These exceptions are caused by the CLR.


2) Application Exception: These exceptions are caused by the
programmer.
What are System Exceptions

An exception that is raised implicitly under a program at runtime by the


Exception Manager (Component of CLR) because of some logical mistakes
(some predefined conditions) is known as System Exception. For example, if
you are diving an integer number by zero, then one system exception is
raised called DivideByZero. Similarly, if you are taking an alphanumeric string
value from the user and trying to store that value in an integer variable, then
one system exception is raised called FormatException. So, in C#, there are
lots of System Exception classes are available. Some of them are as follows:

 DivideByZeroException
 IndexOutOfRangeException
 FormatException
 SQLException
 NullReferenceException, Etc.
What are Application Exceptions

 An exception that is raised explicitly under a program based on our


own condition (i.e. user-defined condition) is known as an application
exception. As a programmer, we can raise application exceptions at
any given point in time. For example, our requirement is that while
performing the division operation, we need to check that if the second
number is an odd number, then we need to throw an exception. This
cannot be handled automatically by the CLR. Then as a user, we need
to create our Custom Exception and we need to create an instance of
our Custom Exception class and we need to throw that Custom
Exception instance using the throw keyword explicitly based on our
business requirement.
 To raise an Application Exception in C#, we need to adopt the
following process. First, we need to create a custom Exception class by
inheriting it from the Parent Exception class and then we need to
create an instance of the Custom Exception class and then we need
to throw that instance.
 While creating and throwing an object of the Exception class manually,
we should not use system exception classes like DivideByZeroException,
FormatException, SQLException, etc. instead we should create our
own Exception class and create and throw an instance of our own
Exception class.

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

The Inner Exception in C# is a property of the Exception class. If you go to the


definition of the Exception class, then you will see that it is a read-only
property. As this property is defined in the parent Exception class, so this
property is available to all the Child classes including the Custom Exception
classes.
Exception Handling Abuse

 Exceptions are nothing but classes that terminate the program


execution abnormally when runtime errors occur during the execution
of a program. For example, when an application is executing a
database query, due to some reason the database connection is lost,
then we will get an SQLException runtime error. Suppose, we are trying
the fetch the data from a text file, and that text file does not exist, then
we will get a File Not Found Exception. So, Exception handling is
generally used to handle these scenarios.
 But sometimes, as a programmer, we are using exception handling
mechanisms to implement programming logic which is bad, and this is
called Exception Handling Abuse in C#.

You might also like