0% found this document useful (0 votes)
19 views24 pages

C# Exception Handling Overview

The document discusses exception handling in C# and event driven programming. It defines exceptions as problems that arise during program execution. It describes structured exception handling using try, catch, and finally blocks. Code within try blocks can generate exceptions, which are passed to matching catch blocks. Finally blocks contain code that always executes after try and catch blocks. The document provides examples of exception classes and implementing exception handlers for methods.

Uploaded by

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

C# Exception Handling Overview

The document discusses exception handling in C# and event driven programming. It defines exceptions as problems that arise during program execution. It describes structured exception handling using try, catch, and finally blocks. Code within try blocks can generate exceptions, which are passed to matching catch blocks. Finally blocks contain code that always executes after try and catch blocks. The document provides examples of exception classes and implementing exception handlers for methods.

Uploaded by

Tess fayye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Arba Minch University

Feb 11, 2024


Institute of Technology
Faculty of Computing & Software Engineering

Event Driven

Event Driven Programming


Programming
(SEngc351)
Mr. Addisu M. (Asst. Prof) G5 SE - Regular
1
Chapter 5

Exception Handling
2

Event Driven Programming Feb 11, 2024


Outline

Feb 11, 2024


 Introducing Exception Handling

 Structured Exception Handling

Event Driven Programming


 Implementing Exception Handling

3
Inheritance and Polymorphism
Polymorphism
 poly means “Many,” and morph means “Forms”
• means “Many Forms”
 allows you to create multiple methods with the same name
but different signatures in the same class or in derived
classes

Intro to Distributed System


 There are two types of polymorphism
 Method Overloading
 Method Overriding

4
Errors

Feb 11, 2024


 Programming errors are generally broken down into three
types: Design-time, Runtime, and Logic errors.
Design Time Errors
 Design-time error is also known as syntax error.
 These occur when the environment you're programming in

Event Driven Programming


doesn't understand your code.
 These are easy to track down in C#, because you get a red
wiggly line pointing them out.
 If you try to run the program, you'll get a dialogue box
popping up telling you that there were Build errors.
5
Errors

Feb 11, 2024


Run Time Errors
 lot harder to track down.
 As their name suggests, occur when the program is running.
 happen when your program tries to do something it shouldn't be
doing

Event Driven Programming


 cause the program to crash
 Ex: trying to access a file
that doesn't exist
 You should write code to
trap runtime errors.

6
Errors

Feb 11, 2024


Logic Errors
 Logic errors also occur when the program is running.
 They happen when your code doesn't quite behave the way you
thought it would.
 A classic example is creating an infinite loop of the type "Do

Event Driven Programming


While x is greater than 10". If x is always going to be greater
than 10, then the loop has no way to exit, and just keeps going
round and round.
 Logic errors tend not to crash your program. But they will
ensure that it doesn't work properly

7
Errors

Feb 11, 2024


 Are events which may be considered exceptional or unusual.
 They are conditions that are detected by an operation, that
cannot be resolved within the local context of the operation and
must be brought to the attention of the operation invoker.
 Exception is a problem that arises during the execution of a

Event Driven Programming


program.
Exception Handler
 Is a procedure or code that deals with the exceptions in your
program.
Raising Exceptions
 The process of noticing exceptions, interrupting the program
and calling the exception handler. 8
Exceptions

Feb 11, 2024


 Are events which may be considered exceptional or unusual.
 They are conditions that are detected by an operation, that
cannot be resolved within the local context of the operation and
must be brought to the attention of the operation invoker.
 An exception is a problem that arises during the execution of a

Event Driven Programming


program.
Exception Handler
 Is a procedure or code that deals with the exceptions in your
program.
Raising Exceptions
 The process of noticing exceptions, interrupting the program
and calling the exception handler. 9
Cont’d…

Feb 11, 2024


Propagating the Exceptions
 Reporting the problem to higher authority (the calling program) in
your program.
Handling the Exceptions
 The process of taking appropriate corrective action.

Event Driven Programming


Example of exceptions
 Array out of bound
 Divide by zero
 File not exit in the given path
 Implicit type casting
 Input/output exception
 Network connections are dropped
 etc… 10
Structured Exception Handling

Feb 11, 2024


 .NET has a built-in class that deals with exceptions.
 The class is called Exception.
 When an exception is found, an exception object is
created.

Event Driven Programming


 exception object contains information relevant to the
error exposed as properties of the object.
 object is an instance of a class that is derived from a
class named [Link].
 The coding structure C# uses to deal with such
Exceptions is called the try … catch structure. 11
C# - Exception Handling

Feb 11, 2024


 Exception is a problem that arises during the
execution of a program.
 C# exception is a response to an exceptional
circumstance that arises while a program is running,
such as an attempt to divide by zero.

Event Driven Programming


 Exceptions are the occurrence of some conditions
that changes the normal flow of execution
 C# exception handling is built upon four keywords:
try, catch, finally and throw.

12
Cont’d…

Feb 11, 2024


 Assuming a block will raise and exception, a method catches an
exception using a combination of the try and catch keywords.
 try/catch block is placed around the code that might generate
an exception.
 Code within a try/catch block is referred to as protected code
 Structure

Event Driven Programming


Try
' normal program code goes here
Catch
' catch block goes here (error handling)
Finally
' finally block goes here

13
Cont’d…

Feb 11, 2024


 Syntax for using try/catch looks like the following:
Try:
 Begins a section of a code in which an exception might be
generated from a code error.
 This section is called the Try Block, means "Try to execute this
code".

Event Driven Programming


 A trapped exception is automatically routed to the Catch
statement.
Catch:
 Begins an exception handler for a type of exception.
 You can list down multiple catch statements to catch different
type of exceptions in case your try block raises more than one
exception in different situations. 14
Cont’d…

Feb 11, 2024


Finally:
 Contains code that runs when the try block finishes normally, or
when a catch block receives control then finishes.
 Is a block that always runs regardless of whether an exception is
detected or not.
 statements that you want to execute, no matter what happens in the

Event Driven Programming


protected code
 Example: closing a database connection.
Throw:
 Sometimes the catch block is unable to handle errors because some
exceptions are so unexpected
 A throw statements is used for that purpose.
 A throw statement ends execution of the exception handler.
 Generates an exception 15
Implementing Exception Handling

Feb 11, 2024


 Exception handlers are implemented for specific
methods.
 The following three general steps are involved in
creating exception handler.
 Wrap the code with which the handler will be associated

Event Driven Programming


in a Try block
 Add one or more Catch block to handle the possible
exceptions
 Add any code that is always executed regardless of
whether or not an exception is thrown to a Finally block
16
Exception Classes in C#

Feb 11, 2024


 C# exceptions are represented by classes.
 The exception classes in C# are mainly directly or indirectly
derived from the [Link] class.
 Some of the exception classes derived from the
[Link] class are:
 [Link] and [Link]

Event Driven Programming


classes
 [Link] class supports exceptions
generated by application programs.
 [Link] class is the base class for all
predefined system exception.
 The following table provides some of the predefined exception
classes derived from the [Link] class 17
Cont’d…

Event Driven Programming Feb 11, 2024


18
Cont’d…

Feb 11, 2024


Exception Class Description
[Link] Handles I/O errors.
[Link] Handles errors generated when a method refers to
on an array index out of range.
[Link] Handles errors generated when type is mismatched
ption with the array type.

Event Driven Programming


[Link] Handles errors generated from deferencing a null
object.
[Link] Handles errors generated from dividing a dividend
with zero.
[Link] Handles errors generated during typecasting.
[Link] Handles errors generated from insufficient free
memory.
[Link] Handles errors generated from stack overflow.
19
Example

Feb 11, 2024


class Program class Program
{ {
static void Main() static void Main()
{ {
try try
{ { // Read in nonexistent file.
int value = 1 / [Link]("0"); using (StreamReader reader =

Event Driven Programming


[Link](value); new StreamReader("not-
} [Link]"))
catch (Exception ex) [Link]();
{ }
catch (FileNotFoundException ex)
[Link]([Link]); { // Write error.
} [Link](ex);
} }
}
} 20
Cont’d…

Event Driven Programming Feb 11, 2024


21
Example: User defined Exceptions

Feb 11, 2024


namespace ExceptionTutorial
{
class AgeException : ApplicationException
{
public AgeException(String message) : base(message)
{
}
}
class TooYoungException : AgeException

Event Driven Programming


{
public TooYoungException(String message) : base(message)
{
}
}
class TooOldException : AgeException
{
public TooOldException(String message) : base(message)
{
}

}
}
22
Creating User-Defined Exceptions

Feb 11, 2024


class TestTemperature public class TempIsZeroException: ApplicationException
{ {
public TempIsZeroException(string message): base(message)
static void Main(string[] args) {
{ }
Temperature temp = new }
Temperature(); public class Temperature
try {

Event Driven Programming


{ int temperature = 0;
public void showTemp()
[Link](); {
} if(temperature == 0)
catch(TempIsZeroException {
e) throw (new TempIsZeroException("Zero Temperature found"));
{ }
[Link]("Temp Is else
Zero Exception"+ {
[Link]("Temperature: “ + temperature); }
[Link]); }
} } 23
}
Feb 11, 2024
The End!
Questions, Ambiguities,

Event Driven Programming


Doubts, … ???
24

Common questions

Powered by AI

Creating user-defined exceptions in C# offers several advantages: it allows developers to handle anticipated unique error conditions specific to the application's domain by creating descriptive error messages tied to that context . This improves error reporting and debugging. User-defined exceptions create a hierarchy of custom exceptions derived from ApplicationException, which can simplify tracking errors specific to different parts of an application and provide enhanced control over error management logic .

Common runtime exceptions in C# include System.DivideByZeroException, which occurs when a division operation is attempted with zero ; System.NullReferenceException, which arises when a null object is dereferenced ; and System.IndexOutOfRangeException, which happens when an array index is accessed out of its bounds . These exceptions stem from programming errors where the application logic fails to anticipate certain scenarios, resulting in runtime errors that disrupt normal execution flow .

Raising exceptions involves detecting an error condition during program execution and notifying the invoking operation through an interrupt that calls an exception handler . This process is crucial in software development because it facilitates the control of unexpected events and error conditions, allowing developers to manage such situations effectively without the application terminating abruptly. Raising exceptions is essential for building robust, user-friendly applications by providing a mechanism to understand and rectify errors as they occur .

The 'finally' keyword in C# exception handling signifies a block of code that will always execute after a try block, regardless of whether an exception was thrown or caught. The 'finally' block is used to release resources, such as closing connections or file streams, or perform other cleanup activities, ensuring resource management consistency and the prevention of memory leaks . This feature supports robust error handling by guaranteeing that critical code executes even when an unexpected situation arises .

Polymorphism contributes to flexible software design by allowing objects to be treated as instances of their parent class, enabling multiple methods with the same name but different implementations either in the same class or derived classes. This allows for method overloading and overriding, enabling one interface with multiple functionalities . This flexibility aids in implementing abstract entities and design patterns, enhancing code reusability and system scalability .

Method overloading and method overriding are two forms of polymorphism in programming. Method overloading occurs when multiple methods have the same name but different parameters within the same class, allowing different implementations based on the input signature . Method overriding, however, involves redefining a base class method in a derived class to provide specialized behavior. While overloading is determined at compile-time, overriding involves late binding, where the derived class method is invoked based on the object type at runtime .

Exception propagation in C# involves passing an unhandled exception to higher levels of the calling chain until it is caught or reaches the application's top level, potentially terminating it . This mechanism supports software reliability by allowing layered handling of errors, where more generic errors can be managed higher up the chain after specific errors are caught lower down. Properly implemented, it helps ensure graceful degradation of application functionality, maintains application responsiveness under failure conditions, and enhances fault tolerance through hierarchical error management strategies .

Exception handling in C# using try-catch-finally blocks enhances program reliability by allowing the programmer to anticipate and manage runtime errors. The try block contains code that may produce an exception, the catch block handles the specific exceptions that could occur, and the finally block executes important code regardless of an exception, such as closing a file stream or releasing resources . This structure prevents abrupt program termination and ensures resource deallocation, maintaining consistent program behavior even in the face of errors .

Runtime errors occur during the execution of a program and often cause the program to crash when it performs an illegal operation, such as accessing a non-existent file . Logic errors, on the other hand, also occur during execution but do not crash the program; instead, they result from incorrect logic which causes the program to operate incorrectly, such as an infinite loop due to a wrong condition .

Structured exception handling is beneficial as it provides a more organized and readable way to manage errors compared to traditional techniques. It uses a defined structure with try, catch, and finally blocks, systematically catching exceptions and executing corrective measures, while ensuring resource cleanup. This minimizes code clutter and facilitates maintenance by decoupling error handling logic from business logic, leading to clearer and more reliable software .

You might also like