CHAPTER FOUR
EXCEPTION HANDLING
Jun 21, 2024 Event Driven Programming
Errors
Jun 21, 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.
2
Cont’d…
Jun 21, 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
cause the program to crash
Event Driven Programming
Ex: trying to access a file
that doesn't exist
You should write code to
trap runtime errors.
3
Cont’d…
Jun 21, 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
Event Driven Programming
"Do 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.
4
Exceptions
Jun 21, 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. 5
Cont’d…
Jun 21, 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… 6
Structured Exception Handling
Jun 21, 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.
exception object contains information relevant to the error
exposed as properties of the object.
Event Driven Programming
object is an instance of a class that is derived from a class named
System.Exception.
The coding structure C# uses to deal with such Exceptions
is called the try … catch structure.
7
C# - Exception Handling
Jun 21, 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.
8
Cont’d…
Jun 21, 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
9
Cont’d…
Jun 21, 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. 10
Cont’d…
Jun 21, 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 11
Implementing Exception Handling
Jun 21, 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
12
Jun 21, 2024
Cont’d…
•Example:
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Event Driven Programming
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
13
Exception Classes in C#
Jun 21, 2024
C# exceptions are represented by classes.
The exception classes in C# are mainly directly or indirectly
derived from the System.Exception class.
Some of the exception classes derived from the
System.Exception class are: System.ApplicationException
and System.SystemException classes
Event Driven Programming
System.ApplicationException class supports exceptions generated by
application programs.
System.SystemException class is the base class for all predefined
system exception.
The following table provides some of the predefined exception
classes derived from the Sytem.SystemException class
14
Cont’d…
• Some of the predefined exception classes derived from the
Sytem.SystemException class
System.IO.IOException: Handles I/O errors
System.IndexOutOfRangeException: Handles errors generated
when a method refers to an array index out of range.
System.ArrayTypeMismatchException: Handles errors generated
when type is mismatched with the array type.
System.NullReferenceException: Handles errors generated from
referencing a null object.
15
Cont’d…
• Some of the predefined exception classes derived from the
Sytem.SystemException class …
System.DivideByZeroException: Handles errors generated from
dividing a dividend with zero.
System.InvalidCastException: Handles errors generated during
typecasting.
System.OutOfMemoryException: Handles errors generated from
insufficient free memory.
System.StackOverflowException: Handles errors generated from
stack overflow.
16
Cont’d…
Event Driven Programming Jun 21, 2024
17
Example
Jun 21, 2024
class Program class Program
{ {
static void Main() static void Main()
{ {
try try
{ { // Read in nonexistent file.
int value = 1 / int.Parse("0"); using (StreamReader reader =
Event Driven Programming
MessageBox.Show(value); new StreamReader("not-
} there.txt"))
catch (Exception ex) reader.ReadToEnd();
{ }
catch (FileNotFoundException ex)
MessageBox.Show(ex.Message); { // Write error.
} MessageBox.Show(ex);
} }
}
} 18
Cont’d…
Event Driven Programming Jun 21, 2024
19
Example: User defined Exceptions
Jun 21, 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)
{
}
}
}
20
Creating User-Defined Exceptions
Jun 21, 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()
temp.showTemp(); {
} if(temperature == 0)
catch(TempIsZeroException {
e) throw (new TempIsZeroException("Zero Temperature found"));
{ }
MessageBox.Show("Temp Is else
Zero Exception"+ {
MessageBox.Show("Temperature: “ + temperature); }
e.Message); }
} } 21
}
Thanks !!
Event Driven Programming Jun 21, 2024
22