SE OOP Lecture10
SE OOP Lecture10
BS – (SOFTWARE ENGINEERING)
LECTURE # 10
1
Lecture Content.
2
Errors in Programming
Types of Errors
Compilation Error
Runtime Error
What is an Exception in Programming?
What is Exception Handling?
What is the Procedure to Handle Exceptions in C#?
Exception handling in C# using Try Catch implementation
Try Block
Catch Block
Syntax to use Exception Handling in C#
Properties of Exception Class in C#:
How to implement Multiple Catch Blocks in C#?
Finally Block
Write the finally block
How many ways we can use try-catch and finally block?
Types of Exceptions
System Exceptions
Application Exceptions
Custom Exceptions
Inner Exception
3
Errors
4
Errors in Programming
5
Errors are the problems or the faults that occur in the program, which
makes the behavior of the program abnormal. Programming errors are
also known as the bugs or faults, and the process of removing these bugs
is known as debugging.
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:
Compilation Errors
Runtime Errors
So, in simple words, we can say that this type of error occurs due to a poor
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.
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.
10
What is an Exception in Programming?
11
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.
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.
So, whenever a runtime error occurs in a program, first the Exception Manager
under the CLR (Common Language Runtime) identifies the type of error that occurs
in the program, then creates an object of the Exception class related to that error
and throws that object which will immediately terminate the program abnormally
on the line where error got occur and display the error message related to that class.
Note: Exception class is the superclass of all Exception classes in C#.
18
What is Exception Handling?
19
The process of catching the exception for converting the CLR given
We can perform any corrective action that may resolve the problem.
Displaying a user-friendly error message, so that the user can resolve the problem provided
if it is under his control.
two reasons.
To stop the Abnormal Termination of the program
Try
Catch
finally
When the exception occurred, the CLR will create an instance of the
Exception class based on the logical error and then throw that Exception
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.
The following image shows the syntax to use exception handling in C#. It starts with the try
block, followed by the catch block, and writing the finally block is optional. You can write
any number of catch blocks for a given try block in C#. This will handle different types of
exceptions thrown by the try block.
Once we use the try and catch blocks in our code the execution takes place as follows:
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).
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.
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.
If a matching catch block is not found, then the generic catch block is going to execute to handle the abnormal
termination.
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.
The catch block without exception class is called a generic catch and the generic catch block in C# can handle any
type of exception that is raised in the corresponding try block. For better understanding, please have a look at the
below example. Here, we created the catch block without any Exception class.
Note: no exception class used in the try block, so it is known as the generic catch block.
The Exception Class is the superclass of all Exception classes and this provides some virtual properties
and methods which are re-implemented by the child classes. If you go to the definition of the Exception
class, then you will see the following.
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.
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. With this kept in mind, let us proceed and see an example
of how to implement Multiple Catch Blocks in C#.
Yes, it is possible. We can catch all exceptions with a single catch block with the parameter Exception. The
Exception class is the superclass of all Child Exception classes and hence it can handle all types of
exceptions thrown in the try block. We need to use this catch block only for stopping the abnormal
termination irrespective of the exceptions thrown from its corresponding try block. For a better
understanding, please have a look at the following example.
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#,
In two ways we can write the finally block. They are as follows:
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 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.
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.
40
Types of Exceptions
41
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:
System Exception: These exceptions are caused by the CLR.
For a better understanding, please have a look at the below image. The Exception is the parent class of
all Exception classes. From the Exception class, SystemException and ApplicationException classes
are defined.
As you can see, for both SystemException and ApplicationException, the parent is
the Exception class only. By default, all the System Exception classes are inherited
from the SystemException class which is inherited from the Exception class and if
we are creating any Application Exception i.e. Custom Exception or user-defined
exception, then that class should and must be inherited from the Exception class,
even we can also create Custom Exception classes inherit from
ApplicationException class.
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.
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.
If none of the already existing .NET exception classes serve our purpose then
we need to go for custom exceptions in C#.
Before creating the Custom Exception class, we need to see the class
definition of the Exception class as our Custom Exception class is going to be
inherited from the parent Exception class.
If you go to the definition of Exception class, then you will see the following.
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.
using System;
namespace ExceptionHandlingDemo
{
//Creating our own Exception Class by inheriting Exception class
public class OddNumberException : Exception
{
//Overriding the Message property
public override string Message
{
get
{
return "Divisor Cannot be Odd Number";
}
}
52
What is Inner Exception?
53
55
56
Point1: First we are asking the user to enter two numbers. In order to understand Inner Exception,
we have to make sure this program causes an exception while running the application. To do that we
have 3 options
You can enter a Character instead of a number which will cause a Format Exception.
Or, you can enter a very big number that an integer cannot hold which will cause Over Flow
Exception.
Or, you can enter zero for the Second Number which will cause the application to throw the Divide
By Zero Exception.
Point2: Once you cause your application to throw an error from the inner try block, then that error is
going to be handled by the Inner Catch block. This is because the inner catch is a generic catch block,
taking the Exception class as a parameter that can capture any type of exceptions thrown from the
corresponding try block.
Point3: Once the catch block catches the exception, then we are trying to log the exception details
into a text file. Here, if you are providing the correct file path, then the exception information will be
logged into the text file. But to understand Inner Exception, make sure that the file path does not exist.
If the File Path does not exist, then we are throwing a File Not Found Exception from the catch block
and if you see, we are passing two parameters to the constructor of the File Not Found Exception class.
The first parameter specifies the message and the second parameter is the exception (the exception
that was thrown from the inner try block) and this exception information will be stored inside the
InnerException property.
Point4: Now, the outer catch block will catch the File Not Found Exception which is thrown by the
inner catch block. Here, first, we are printing the current exception details and then we are printing
the original or the old exception details i.e. the exception which is originally thrown from the Inner Try
block. And we can access the old exception details from the Inner Exception property. But before
accessing the InnnerExveption properties, please make sure that the InnnerExveption value is not
null, else you might get a Null Reference Exception.
Now, run the application and provide the two input numbers as 100 and 0 and this time,
the inner try block will throw Divide By Zero Exception and you will see that this Divide
By Zero Exception details will be printed by Inner Exception as shown in the below
image.
Now, run the application and provide the second value as abc and this time, the inner try
block will throw Format Exception and you will see that this Format Exception details
will be printed by Inner Exception as shown in the below image.
THANK YOU.
61