0% found this document useful (0 votes)
5 views61 pages

SE OOP Lecture10

Uploaded by

Ali Uskuplo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views61 pages

SE OOP Lecture10

Uploaded by

Ali Uskuplo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

OBJECT ORIENTED PROGRAMMING

BS – (SOFTWARE ENGINEERING)

FALL SEMESTER - 2023

LECTURE # 10

COURSE INSTRUCTOR: AMJAD ALI KHAWAJA

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

Object Oriented Programming Fall-2023


Any Queries From
Previous Lectures

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.

Object Oriented Programming Fall-2023


Types of Errors
6

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

Object Oriented Programming Fall-2023


Compilation Error
7

 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.

Object Oriented Programming Fall-2023


Runtime Error
8

 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.

Object Oriented Programming Fall-2023


Is Runtime Errors are Dangerous?
9

 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.

Object Oriented Programming Fall-2023


Exception

10
What is an Exception in Programming?
11

 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.

Object Oriented Programming Fall-2023


Who is Responsible for the Abnormal Termination of the
Program whenever Runtime Errors occur?
12

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
 IndexOutOfRangeException
 FormatException
 NullReferenceException
 DivideByZeroException
 FileNotFoundException
 SQLException,
 OverFlowException, etc.

Object Oriented Programming Fall-2023


Who is Responsible for the Abnormal Termination of the
Program whenever Runtime Errors occur?
13

 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#.

Object Oriented Programming Fall-2023


What happens if an Exception is Raised in the Program?
14

When an Exception is raised in C#, the program


execution is terminated abnormally. That means the
statements placed after the exception-causing
statements are not executed but the statements placed
before that exception-causing statement are executed
by CLR.

Object Oriented Programming Fall-2023


What CLR does when an Exception Occurred in the program?
15

The CLR creates the exception class object that is


associated with that logical mistake (exception) and
terminates the program execution by throwing that
exception object by using the throw keyword. So, we
can say an exception is an event that occurs during the
execution of a program that disrupts the normal flow
of instruction execution.

Object Oriented Programming Fall-2023


Program Execution without Exception in C#
16

The following C# example shows program execution


without exception. This is a very simple program, we
are just dividing two numbers and printing the result
on the console.

Object Oriented Programming Fall-2023


Program Execution with Exception in C#
17

The following C# example shows program execution


with exception.

Object Oriented Programming Fall-2023


Exception Handling

18
What is Exception Handling?
19

 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
 We can stop the Abnormal Termination

 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.

Object Oriented Programming Fall-2023


Why do we need Exception Handling?
20

 We need Exception Handling in C# because of the following

two reasons.
 To stop the Abnormal Termination of the program

 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.

Object Oriented Programming Fall-2023


What is the Procedure to Handle Exceptions in C#?
21

The Exception Handling in C# is a 4 steps procedure


 Preparing the exception object that is appropriate to the
current logical mistake.

 Throwing that exception to the appropriate exception handler.

 Catching that exception

 Taking necessary actions against that exception

Object Oriented Programming Fall-2023


How can we handle an Exception in .NET?
22

There are two methods to handle the exception in


.NET
 Logical Implementation

 Try Catch Implementation

Object Oriented Programming Fall-2023


What is the Logical Implementation in C# to Handle
Exception?
23

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.

Object Oriented Programming Fall-2023


Example of Logical Exception
24

Object Oriented Programming Fall-2023


Exception handling in C# using Try Catch implementation
25

To implement the try-catch implementation, the .NET


framework provides three keywords. They are as follows:

 Try

 Catch

 finally

Object Oriented Programming Fall-2023


Try Block
26

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.

Object Oriented Programming Fall-2023


Catch Block
27

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.

Object Oriented Programming Fall-2023


Syntax to use Exception Handling in C#
28

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.

Object Oriented Programming Fall-2023


try and catch blocks in our code the execution
29

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.

Note: Here, we are showing the try-and-catch block execution.

Object Oriented Programming Fall-2023


Example to Handle an Exception using Try-Catch
Implementation with Generic Catch Block in C#
30

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.

Object Oriented Programming Fall-2023


Properties of Exception Class in C#
31

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.

Object Oriented Programming Fall-2023


Example -- Properties of Exception Class in C#:
32

Object Oriented Programming Fall-2023


How to implement Multiple Catch Blocks in C#?
33

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#.

Object Oriented Programming Fall-2023


Is it possible to catch all exceptions using a single catch block?
34

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.

Object Oriented Programming Fall-2023


When should we write Multiple Catch Blocks in C# for a Single Try block?
35

We need to write multiple catch blocks in C# for a single try block because
of the following reasons

 To print messages specific to an exception or

 To execute some logic specific to an exception

Object Oriented Programming Fall-2023


Finally Block
36

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#,

Object Oriented Programming Fall-2023


Write the finally block
37

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.

Object Oriented Programming Fall-2023


In how many ways we can use try-catch and finally block?
38

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.

Object Oriented Programming Fall-2023


Example to Understand Try-Finally Block without Catch Block:
39

Object Oriented Programming Fall-2023


Types of Exception

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.

 Application Exception: These exceptions are caused by the programmer.

 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.

Object Oriented Programming Fall-2023


Types of Exceptions
42

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.

Object Oriented Programming Fall-2023


What are System Exceptions?
43

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.

Object Oriented Programming Fall-2023


What are Application Exceptions?
44

 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.

Object Oriented Programming Fall-2023


What are Application Exceptions?
45

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.

Object Oriented Programming Fall-2023


What is Custom Exceptions?
46

 Custom Exception means create your own exception to handle error.

 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.

Object Oriented Programming Fall-2023


How to Create Own Custom Exception Class in C#?
47

If you go to the definition of Exception class, then you will see the following.

Object Oriented Programming Fall-2023


How to Create Own Custom Exception Class in C#?
48

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.

Object Oriented Programming Fall-2023


Example – Create Custom Exceptions in C#?
49

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";
}
}

Object Oriented Programming Fall-2023


Example – Create Custom Exceptions in C#?
50

//Overriding the HelpLink Property


public override string HelpLink
{
get
{
return "Get More Information from here: ";
}
}
}
}

Object Oriented Programming Fall-2023


Example – Create Custom Exceptions in C#?
51

Object Oriented Programming Fall-2023


Inner Exception

52
What is Inner Exception?
53

 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 i.e. having only get accessor as shown in the below image. 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.
 public Exception InnerException {get;}: This InnerException property
gets the Exception instance that caused the current exception. It returns an
object that describes the error that caused the current exception. The
InnerException property returns the same value that passed into the
constructor, or null if the inner exception value was not supplied to the
constructor.

Object Oriented Programming Fall-2023


What is Inner Exception in C#?
54

Object Oriented Programming Fall-2023


Example of Inner
Exception

55
56

Object Oriented Programming Fall-2023


Example of Inner Exceptions in C#?
57

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.

Object Oriented Programming Fall-2023


Example of Inner Exceptions in C#?
58

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.

Object Oriented Programming Fall-2023


Example of Inner Exceptions in C#? -- Output1:
59

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.

Object Oriented Programming Fall-2023


Example of Inner Exceptions in C#? – Output2:
60

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.

Object Oriented Programming Fall-2023


You have the quality of education, life give
you more opportunity for new area of
learning to achieve your dreams.

THANK YOU.

61

You might also like